如果行的某个元素不满足条件,我怎么能删除数组的行?

时间:2013-09-25 17:00:43

标签: python numpy

当数组第三列的元素小于特定数量时,我想删除数组的行。例如:

a=np.array([[2331.13,1944.88,23.1379,7,3.18339,0.482105],
[8168.44,1904.70,19.5025,265,4.12642,0.0376510],
[7389.36,1983.97,14.3581,3937,6.04109,0.713416],
[1765.18,1944.29,22.5495,35,2.30717,0.794432],
[2319.33,1946.68,22.4300,25,3.63676,0.0210690],
[785.666,2090.69,14.7940,1095,2.52823,0.999842],
[4071.24,2186.92,22.6616,31,2.79309,0.0312501],
[7082.51,2191.69,23.0122,19,2.53166,0.687001]])

我想删除满足以下条件的行:

a[:,2]<15.0

干杯。

2 个答案:

答案 0 :(得分:6)

你可以这样做:

a[a[:,2]>=15.0, :]

请注意a[:,2]<15.0a[:,2]>=15.0的反转,以便您描述要保留而不是删除的行

如果反转您的情况不是那么简单,您还可以使用~

a[~(a[:,2]<15.0), :]

答案 1 :(得分:0)

我认为删除行或列的最直接方法是使用np.delete

>>> a = np.arange(16).reshape(4,4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> a[:,2]
array([ 2,  6, 10, 14])
>>> to_remove = a[:,2] < 7
>>> to_remove
array([ True,  True, False, False], dtype=bool)
>>> new_a = np.delete(a, to_remove, axis=0)
>>> new_a
array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])

在一行中:

new_a = np.delete(a, a[:,2] < 7, axis=0)