删除3D numpy数组中包含负值的“行”

时间:2021-01-08 21:38:09

What I have:

>>> forces
array([[[  63.82078252,    0.63841691],
        [ -62.45826693,    7.11946976],
        [ -87.85946925,   15.1988562 ],
        [-120.49417797,  -16.31785819],
        [ -81.36080338,    6.45074645]],

       [[ 364.99959095,    4.92473888],
        [ 236.5762723 ,   -7.22959548],
        [  69.55657789,    1.20164815],
        [ -22.1684177 ,   13.42611095],
        [ -91.19739147,  -16.15076634]]])

forces[0] and forces [1] each contain a list of paired values, e.g. 63.82078252 & 0.63841691 are one data point.

强制[0]和强制[1]包含成对值的列表,例如,63.82078252和0.63841691是一个数据点。

I want to remove all pairs where the first value is negative:

>>> forces
array([[[  63.82078252,    0.63841691]],

       [[ 364.99959095,    4.92473888],
        [ 236.5762723 ,   -7.22959548],
        [  69.55657789,    1.20164815]]])

But this type of structure is not possible since the two slices of forces have different sizes: (1, 2) and (3, 2) respectively.

但这种结构是不可能的,因为这两种力的大小不同:(1,2)和(3,2)。

My sloppy attempt:

>>> forces[:,:,0][forces[:,:,0] < 0] = np.nan
>>> forces
array([[[  63.82078252,    0.63841691],
        [          nan,    7.11946976],
        [          nan,   15.1988562 ],
        [          nan,  -16.31785819],
        [          nan,    6.45074645]],

       [[ 364.99959095,    4.92473888],
        [ 236.5762723 ,   -7.22959548],
        [  69.55657789,    1.20164815],
        [          nan,   13.42611095],
        [          nan,  -16.15076634]]])

and then using isnan to remove the relevant entries:

然后使用isnan删除相关条目:

>>> forces = forces[~np.isnan(forces).any(axis=2)]
>>> forces
array([[  63.82078252,    0.63841691],
       [ 364.99959095,    4.92473888],
       [ 236.5762723 ,   -7.22959548],
       [  69.55657789,    1.20164815]])

So these are the correct values but they are now lumped together into a 2D array.

这些是正确的值但现在它们被合并成一个二维数组。

How can I create a heterogeneously sized "array" that will contain two slices of size (1, 2) and (3, 2) respectively, for this simplified example?

Also any pointers on accomplishing the task more elegantly would be much appreciated!

此外,任何关于如何更优雅地完成任务的建议都将非常感谢!

1 个解决方案

#1


6  

It is simply

它仅仅是

forces[forces[..., 0] >= 0]

Read more here: http://scipy-lectures.github.io/intro/numpy/array_object.html#fancy-indexing

阅读更多:http://scipy-lectures.github.io/intro/numpy/array_object.html变址

#1


6  

It is simply

它仅仅是

forces[forces[..., 0] >= 0]

Read more here: http://scipy-lectures.github.io/intro/numpy/array_object.html#fancy-indexing

阅读更多:http://scipy-lectures.github.io/intro/numpy/array_object.html变址