[英]Assigning to slices of 2D NumPy array
I want to assign 0
to different length slices of a 2d array. 我想将
0
分配给2d数组的不同长度的切片。
Example: 例:
import numpy as np
arr = np.array([[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]])
idxs = np.array([0,1,2,0])
Given the above array arr
and indices idxs
how can you assign to different length slices. 给定上述数组
arr
和索引idxs
,您如何分配给不同的长度切片。 Such that the result is: 这样的结果是:
arr = np.array([[0,2,3,4],
[0,0,3,4],
[0,0,0,4],
[0,2,3,4]])
These don't work 这些不起作用
slices = np.array([np.arange(i) for i in idxs])
arr[slices] = 0
arr[:, :idxs] = 0
You can use broadcasted comparison to generate a mask, and index into arr
accordingly: 您可以使用广播比较生成掩码,并相应地索引到
arr
:
arr[np.arange(arr.shape[1]) <= idxs[:, None]] = 0
print(arr)
array([[0, 2, 3, 4],
[0, 0, 3, 4],
[0, 0, 0, 4],
[0, 2, 3, 4]])
This does the trick: 这可以解决问题:
import numpy as np
arr = np.array([[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]])
idxs = [0,1,2,0]
for i,j in zip(range(arr.shape[0]),idxs):
arr[i,:j+1]=0
Here is a sparse solution that may be useful in cases where only a small fraction of places should be zeroed out: 这是一个稀疏解决方案,在只有一小部分地方应归零的情况下可能有用:
>>> idx = idxs+1
>>> I = idx.cumsum()
>>> cidx = np.ones((I[-1],), int)
>>> cidx[0] = 0
>>> cidx[I[:-1]]-=idx[:-1]
>>> cidx=np.cumsum(cidx)
>>> ridx = np.repeat(np.arange(idx.size), idx)
>>> arr[ridx, cidx]=0
>>> arr
array([[0, 2, 3, 4],
[0, 0, 3, 4],
[0, 0, 0, 4],
[0, 2, 3, 4]])
Explanation: We need to construct the coordinates of the positions we want to put zeros in. 说明:我们需要构造要放入零的位置的坐标。
The row indices are easy: we just need to go from 0 to 3 repeating each number to fill the corresponding slice. 行索引很简单:我们只需要从0到3重复每个数字以填充相应的切片即可。
The column indices start at zero and most of the time are incremented by 1. So to construct them we use cumsum on mostly ones. 列索引从零开始,并且大多数时候都以1递增。因此,为了构造它们,我们对大多数索引使用cumsum。 Only at the start of each new row we have to reset.
仅在每个新行的开头,我们才需要重置。 We do that by subtracting the length of the corresponding slice such as to cancel the ones we have summed in that row.
我们通过减去相应切片的长度来做到这一点,例如取消我们在该行中求和的切片的长度。
import numpy as np
arr = np.array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
idxs = np.array([0, 1, 2, 0])
for i, idx in enumerate(idxs):
arr[i,:idx+1] = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.