使用布尔索引就地修改numpy数组节 [英] Modify numpy array section in-place using boolean indexing
问题描述
给出2D numpy数组,即;
Given a 2D numpy array, i.e.;
import numpy as np
data = np.array([
[11,12,13],
[21,22,23],
[31,32,33],
[41,42,43],
])
我需要针对所需的行和列,基于两个掩蔽向量修改子阵列;
I need modify in place a sub-array based on two masking vectors for the desired rows and columns;
rows = np.array([False, False, True, True], dtype=bool)
cols = np.array([True, True, False], dtype=bool)
就是这样;
print data
#[[11,12,13],
# [21,22,23],
# [0,0,33],
# [0,0,43]]
推荐答案
Now that you know how to access the rows/cols you want, just assigne the value you want to your subarray. It's a tad trickier, though:
mask = rows[:,None]*cols[None,:]
data[mask] = 0
原因是,当我们以data[rows][:,cols]
的形式访问子数组时(如您的
The reason is that when we access the subarray as data[rows][:,cols]
(as illustrated in your previous question, we're taking a view of a view, and some references to the original data get lost in the way.
相反,这里我们通过广播您的两个1D数组rows
和cols
彼此构建一个2D布尔数组.您的mask
数组现在具有形状(len(rows),len(cols)
.我们可以使用mask
直接访问data
的原始项目,并将它们设置为新值.请注意,当您执行data[mask]
时,将获得一维数组,这不是您在
Instead, here we construct a 2D boolean array by broadcasting your two 1D arrays rows
and cols
one with the other. Your mask
array has now the shape (len(rows),len(cols)
. We can use mask
to directly access the original items of data
, and we set them to a new value. Note that when you do data[mask]
, you get a 1D array, which was not the answer you wanted in your previous question.
要构造掩码,可以使用&
运算符代替*
(因为我们正在处理布尔数组),或更简单的
To construct the mask, we could have used the &
operator instead of *
(because we're dealing with boolean arrays), or the simpler np.outer
function:
mask = np.outer(rows,cols)
为np.outer
解决方案提供@Marcus Jones的道具.
props to @Marcus Jones for the np.outer
solution.
这篇关于使用布尔索引就地修改numpy数组节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!