简体   繁体   English

删除 numpy 数组的一些行

[英]Delete some rows of a numpy array

I have a numpy array like below我有一个 numpy 数组,如下所示


cf = 
[[ 0.06605101 -0.37910558]
 [ 0.01950959 -0.13871163]
 [-0.07609168  0.35762712]
 [-0.10962792  0.53259178]
 [-0.20441798  1.02187988]
 [-0.27493986  1.3927189 ]
 [-0.32651418  1.66157985]
 [ 0.1344195  -0.73359827]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [ 0.          0.        ]
 [-0.01140529  0.02146107]
 [-0.14210564  0.70305015]
 [ 0.19425714 -1.04428677]
 [ 0.21070736 -1.13055805]
 [ 0.24264512 -1.29770194]
 [ 0.2739207  -1.45405194]
 [ 0.34871618 -1.84201387]
 [ 0.41549682 -2.18784216]
 [ 0.48779434 -2.56516974]
 [ 0.61753187 -3.22472257]
 [ 0.62543066 -3.29968867]
 [ 0.67363223 -3.51593344]
 [ 0.67156065 -3.50685949]
 [ 0.67066598 -3.5027474 ]
 [ 0.61698089 -3.20216463]
 [ 0.33951472 -1.80812563]
 [ 0.16105593 -0.88319653]]

But I would like to delete rows that values are [ 0. 0. ] .但我想删除值为[ 0. 0. ]的行。

To do that, my code is为此,我的代码是

for idx in range(cf.shape[0]):
    if cf[idx,0] == 0 and cf[idx,1] == 0 :
        np.delete(cf,idx,0)

But cf is nothing changed.cf没有任何改变。 What is the problem..?问题是什么..? Are the [ 0. 0. ] values not exactly zero? [ 0. 0. ]值不完全为零吗?

Take advantage of numpy's vectorized methods.利用 numpy 的矢量化方法。 Say your array is a :假设您的数组a

trimmed = cf[(cf != 0).any(axis=1)]

This will return the rows where all the values don't sum up to zero:这将返回所有值总和不为零的行:

cf[np.abs(cf).sum(axis=1) != 0]

You can use boolean filtering, selecting rows where the absolute values don't sum to zero:您可以使用 boolean 过滤,选择绝对值总和不为零的行:

>>> cf[np.abs(cf).sum(1) != 0]
array([[ 0.06605101, -0.37910558],
       [ 0.01950959, -0.13871163],
       [-0.07609168,  0.35762712],
       [-0.10962792,  0.53259178],
       [-0.20441798,  1.02187988],
       [-0.27493986,  1.3927189 ],
       [-0.32651418,  1.66157985],
       [ 0.1344195 , -0.73359827],
       [-0.01140529,  0.02146107],
       [-0.14210564,  0.70305015],
       [ 0.19425714, -1.04428677],
       [ 0.21070736, -1.13055805],
       [ 0.24264512, -1.29770194],
       [ 0.2739207 , -1.45405194],
       [ 0.34871618, -1.84201387],
       [ 0.41549682, -2.18784216],
       [ 0.48779434, -2.56516974],
       [ 0.61753187, -3.22472257],
       [ 0.62543066, -3.29968867],
       [ 0.67363223, -3.51593344],
       [ 0.67156065, -3.50685949],
       [ 0.67066598, -3.5027474 ],
       [ 0.61698089, -3.20216463],
       [ 0.33951472, -1.80812563],
       [ 0.16105593, -0.88319653]])

​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM