屏蔽时 Numpy 数组丢失维度 [英] Numpy array loss of dimension when masking

查看:27
本文介绍了屏蔽时 Numpy 数组丢失维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择数组的某些元素并根据这些值执行加权平均计算.但是,使用过滤条件会破坏数组的原始结构.形如 (2, 2, 3, 2)arr 变成了一个一维数组.这对我来说没有用,因为并非所有这些元素都需要稍后相互组合(但它们的子数组).我怎样才能避免这种扁平化?

<预><代码>>>>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] ]]])>>>阿尔数组([[[[ 1, 11],[2, 22],[3, 33]],[[4, 44],[5, 55],[6, 66]]],[[[ 7, 77],[8, 88],[9, 99]],[[ 0, 32],[1, 33],[ 2, 34]]]])>>>形状(2, 2, 3, 2)>>>arr[arr>3]数组([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

要保持相同的维度,您将需要一个填充值.在下面的示例中,我使用 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 数组丢失维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆