kha*_*han 15 python arrays numpy
在给定的numpy数组中X:
X = array([1,2,3,4,5,6,7,8,9,10])
Run Code Online (Sandbox Code Playgroud)
我想分别替换索引(2, 3)和(7, 8)单个元素-1,如:
X = array([1,2,-1,5,6,7,-1,10])
Run Code Online (Sandbox Code Playgroud)
换句话说,我用一个奇异的值替换了索引(2, 3)和(7,8)原始数组的值.
问题是:它周围是否有一种numpy-ish方式(即没有for循环和使用python列表)?谢谢.
注意:这不等于用另一个元素就地替换单个元素.它用"奇异"值替换多个值.谢谢.
使用numpy.delete类似于@pault的解决方案,但由于它使用纯粹的numpy索引,因此效率更高.但是,由于这种有效的索引,这意味着您不能将锯齿状数组作为索引传递
建立
a = np.array([1,2,3,4,5,6,7,8,9,10])
idx = np.stack([[2, 3], [7, 8]])
Run Code Online (Sandbox Code Playgroud)
a[idx] = -1
np.delete(a, idx[:, 1:])
Run Code Online (Sandbox Code Playgroud)
array([ 1, 2, -1, 5, 6, 7, -1, 10])
Run Code Online (Sandbox Code Playgroud)
尝试np.put:
np.put(X, [2,3,7,8], [-1,0]) # `0` can be changed to anything that's not in the array
print(X[X!=0]) # whatever You put as an number in `put`
Run Code Online (Sandbox Code Playgroud)
所以基本上用put做索引的值,然后删除零值。
或者正如 @khan 所说,可以做一些超出范围的事情:
np.put(X, [2,3,7,8], [-1,np.max(X)+1])
print(X[X!=X.max()])
Run Code Online (Sandbox Code Playgroud)
所有输出:
[ 1 2 -1 5 6 7 -1 10]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1340 次 |
| 最近记录: |