问题描述
我想选择数组的某些元素并根据这些值执行加权平均计算.但是,使用过滤条件会破坏数组的原始结构.形如 (2, 2, 3, 2)
的 arr
变成了一个一维数组.这对我来说没有用,因为并非所有这些元素都需要稍后相互组合(但它们的子数组).我怎样才能避免这种扁平化?
Checkout 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]]]])
I want to select certain elements of an array and perform a weighted average calculation based on the values. However, using a filter condition, destroys the original structure of the array. arr
which was of shape (2, 2, 3, 2)
is turned into a 1-dimensional array. This is of no use to me, as not all these elements need to be combined later on with each other (but subarrays of them). How can I avoid this flattening?
>>> 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,)
Checkout numpy.where
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
To keep the same dimensionality you are going to need a fill value. In the example below I use 0, but you could also use np.nan
np.where(arr>3, arr, 0)
returns
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]]]])
这篇关于屏蔽时 Numpy 数组丢失维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!