我想索引一个2dndarray并获取这个ndarray的一个子集。然后,我将这个子集ndarray分配给与这个子集ndarray具有相同形状的另一个ndarry。但是原始的ndarray没有改变。
这里有一个例子,赋值操作后mat
没有改变。
我想要的是分配一个具有另一个ndarray.
的subset of ndarray
import numpy as np
ma = np.array([1,2,3,4,5] * 5).reshape(5,5)
mask = np.array([False, True, False, True, True])
sub = np.array([[100,101, 102],
[103, 104, 105],
[106,107,108]])
ma[mask][:,mask] = sub
print(ma)
我所期望的是:
array([[1, 1, 3, 1, 5],
[1, 100, 1, 101, 102],
[1, 1, 3, 1, 5],
[1, 103, 3, 104, 105],
[1, 106, 3, 107, 108]])
但是mat没有改变:
array([[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5]])
发布于 2019-05-13 17:20:40
np.where(mask, 1, np.where(mask, 1, ma).T).T
np.where(mask, 1, ma)
使用掩码替换为columnsnp.where(mask, 1, np.where(mask, 1, ma).T)
中的1转置结果,然后再次重复以掩码rowsnp.where(mask, 1, np.where(mask, 1, ma).T).T
转置返回输出
np.where(mask, 1, np.where(mask, 1, ma).T).T
array([[1, 1, 3, 1, 5],
[1, 1, 1, 1, 1],
[1, 1, 3, 1, 5],
[1, 1, 1, 1, 1],
[1, 1, 3, 1, 5]])
发布于 2019-05-13 17:28:52
执行以下操作:
ma[np.ix_(mask, mask)] = sub
https://stackoverflow.com/questions/56108865
复制相似问题