如何在numpy中删除具有相同值的列

时间:2017-10-17 19:53:45

标签: python numpy matrix

如何删除NumPy数组中具有相同值的所有列?

例如,如果我有这个矩阵:

[0 1 2 3 1]  
[0 2 2 1 0]  
[0 4 2 3 4]  
[0 1 2 3 4]  
[0 1 2 4 5]

我想得到一个看起来像这样的新矩阵:

[1 3 1]  
[2 1 0]  
[4 3 4]  
[1 3 4]  
[1 4 5]

2 个答案:

答案 0 :(得分:3)

您可以将数组与其自身的移位版本进行比较,如果列的所有对都相等,则该列只包含一个唯一值,可以使用布尔索引删除:

a[:, ~np.all(a[1:] == a[:-1], axis=0)]

#array([[1, 3, 1],
#       [2, 1, 0],
#       [4, 3, 4],
#       [1, 3, 4],
#       [1, 4, 5]])

答案 1 :(得分:2)

假设

import numpy
a = numpy.array([[0, 1, 2, 3, 1],
                 [0, 2, 2, 1, 0],
                 [0, 4, 2, 3, 4],
                 [0, 1, 2, 3, 4],
                 [0, 1, 2, 4, 5]])

然后

b = a == a[0,:]   # compares first row with all others using broadcasting
# b: array([[ True,  True,  True,  True,  True],
#           [ True, False,  True, False, False],
#           [ True, False,  True,  True, False],
#           [ True,  True,  True,  True, False],
#           [ True,  True,  True, False, False]], dtype=bool)

沿着行使用all充当行and操作(感谢Divakar!):

c = b.all(axis=0)
# c: array([ True, False,  True, False, False], dtype=bool)

可用于布尔索引

a[:, ~c]
Out: 
array([[1, 3, 1],
       [2, 1, 0],
       [4, 3, 4],
       [1, 3, 4],
       [1, 4, 5]])

作为一个丑陋的oneliner:

a[:, ~(a == a[0,:]).all(0)]