蒙版时数组的尺寸损失
我想选择数组的某些元素,然后根据这些值执行加权平均计算。但是,使用过滤条件会破坏数组的原始结构。arr
形状(2, 2, 3,
2)
已变成一维数组。这对我来说毫无用处,因为并非所有这些元素以后都需要组合在一起(而是它们的子数组)。如何避免这种变平?
>>> arr = np.asarray([ [[[1, 11], [2, 22], [3, 33]], [[4, 44], [5, 55], [6, 66]]], [ [[7, 77], [8, 88], [9, 99]], [[0, 32], [1, 33], [2, 34] ]] ])
>>> arr
array([[[[ 1, 11],
[ 2, 22],
[ 3, 33]],
[[ 4, 44],
[ 5, 55],
[ 6, 66]]],
[[[ 7, 77],
[ 8, 88],
[ 9, 99]],
[[ 0, 32],
[ 1, 33],
[ 2, 34]]]])
>>> arr.shape
(2, 2, 3, 2)
>>> arr[arr>3]
array([11, 22, 33, 4, 44, 5, 55, 6, 66, 7, 77, 8, 88, 9, 99, 32, 33,
34])
>>> arr[arr>3].shape
(18,)
-
查看
numpy.where
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
为了保持相同的尺寸,您将需要一个填充值。在下面的示例中,我使用0,但您也可以使用
np.nan
np.where(arr>3, arr, 0)
退货
array([[[[ 0, 11], [ 0, 22], [ 0, 33]], [[ 4, 44], [ 5, 55], [ 6, 66]]], [[[ 7, 77], [ 8, 88], [ 9, 99]], [[ 0, 32], [ 0, 33], [ 0, 34]]]])