根据单个单元格上的条件从numpy数组中删除行

时间:2014-01-09 09:49:26

标签: python arrays numpy

最重要的是,抱歉我的英语不好。

我有这个数组t

array([[ 0,  1,  2,  0,  4,  5,  6,  7,  8,  9],
       [ 0, 11,  0, 13,  0, 15,  0, 17, 18,  0]])

我想删除第二行值为null的列。在这里,我想删除列0,2,4,6和9,以获得此数组:

array([[  1,   0,   5,   7,  8 ],
       [ 11,  13,  15,  17, 18 ]])

我尝试使用np.sum()但未成功。

5 个答案:

答案 0 :(得分:14)

与Juh_类似,但更具表现力,并避免一些轻微的不必要的性能开销。总共12个高度pythonic,显性和unambigious字符。这真的是numpy 101;如果你还在试图绕过这个问题,你可以通过阅读一个简单的底漆来帮助自己。

import numpy as np
a = np.array([[ 0,  1,  2,  0,  4,  5,  6,  7,  8,  9],
              [ 0, 11,  0, 13,  0, 15,  0, 17, 18,  0]])
print a[:,a[1]!=0]

答案 1 :(得分:3)

使用numpy.delete

a = np.array([[0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])

indices = [i for (i,v) in enumerate(a[1]) if v==0]
# [0, 2, 4, 6, 9]

a = np.delete(a, indices, 1)
# array([[ 1,  0,  5,  7,  8], [11, 13, 15, 17, 18]])

答案 2 :(得分:2)

简单(完全numpy)解决方案:

import numpy as np

t = np.array([[ 0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [ 0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])
indices_to_keep = t[1].nonzero()[0]

print t[:,indices_to_keep]
# [[ 1  0  5  7  8]
#  [11 13 15 17 18]]

答案 3 :(得分:2)

使用np.where

>>> t.T[np.where(t[1])].T
array([[ 1,  0,  5,  7,  8],
       [11, 13, 15, 17, 18]])

答案 4 :(得分:0)

我的工作方式如下:

data = array([[ 0, 1, 2, 0, 4, 5, 6, 7, 8, 9], [ 0, 11, 0, 13, 0, 15, 0, 17, 18, 0]])
res = array([(a, b,) for a, b in zip(data[0], data[1]) if b]).transpose()

得到了结果

In [23]: res
Out[23]: 
array([[ 1,  0,  5,  7,  8],
       [11, 13, 15, 17, 18]])