目录

赋值

目录

赋值

Dask 数组支持大多数 NumPy 的赋值索引语法。具体来说,它支持以下组合:

  • 通过整数索引:x[1] = y

  • 通过切片索引:x[2::-1] = y

  • 通过整数列表索引:x[[0, -1, 1]] = y

  • 通过一维 numpy 整数数组索引:x[np.arange(3)] = y

  • 通过一维 Array 整数数组索引:x[da.arange(3)] = y, x[da.from_array([0, -1, 1])] = y, x[da.where(np.array([1, 2, 3]) < 3)[0]] = y

  • 通过布尔列表索引:x[[False, True, True]] = y

  • 通过一维 numpy 布尔数组索引:x[np.arange(3) > 0] = y

它还支持

  • 通过一个可广播的 Array 布尔数组索引:x[x > 0] = y

但是,目前不支持以下方式:

  • 在多个轴上使用列表索引:x[[1, 2, 3], [3, 1, 2]] = y

广播

应用正常的 NumPy 广播规则

>>> x = da.zeros((2, 6))
>>> x[0] = 1
>>> x[..., 1] = 2.0
>>> x[:, 2] = [3, 4]
>>> x[:, 5:2:-2] = [[6, 5]]
>>> x.compute()
array([[1., 2., 3., 5., 1., 6.],
       [0., 2., 4., 5., 0., 6.]])
>>> x[1] = -x[0]
>>> x.compute()
array([[ 1.,  2.,  3.,  5.,  1.,  6.],
       [-1., -2., -3., -5., -1., -6.]])

掩码

可以通过赋值给 NumPy 掩码值或带有掩码值的数组来掩码元素

>>> x = da.ones((2, 6))
>>> x[0, [1, -2]] = np.ma.masked
>>> x[1] = np.ma.array([0, 1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0, 0])
>>> print(x.compute())
[[1.0 -- 1.0 1.0 -- 1.0]
 [0.0 -- -- 3.0 4.0 5.0]]
>>> x[:, 0] = x[:, 1]
>>> print(x.compute())
[[1.0 -- 1.0 1.0 -- 1.0]
 [0.0 -- -- 3.0 4.0 5.0]]
>>> x[:, 0] = x[:, 1]
>>> print(x.compute())
[[-- -- 1.0 1.0 -- 1.0]
 [-- -- -- 3.0 4.0 5.0]]

当且仅当提供一个可广播的 Array 布尔数组时,掩码数组赋值目前无法按预期工作。在这种情况下,会赋值给掩码底层的数据

>>> x = da.arange(12).reshape(2, 6)
>>> x[x > 7] = np.ma.array(-99, mask=True)
>>> print(x.compute())
[[  0   1   2   3   4   5]
 [  6   7 -99 -99 -99 -99]]

注意,当在索引的元组或隐式元组中使用布尔型 Array 索引时,掩码赋值是有效的

>>> x = da.arange(12).reshape(2, 6)
>>> x[1, x[0] > 3] = np.ma.masked
>>> print(x.compute())
[[0 1 2 3 4 5]
 [6 7 8 9 -- --]]
>>> x = da.arange(12).reshape(2, 6)
>>> print(x.compute())
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
>>> x[(x[:, 2] < 4,)] = np.ma.masked
>>> print(x.compute())
[[-- -- -- -- -- --]
 [6 7 8 9 10 11]]