在Python中从数组中删除列

时间:2013-07-22 16:17:42

标签: python numpy

我有一个2D Python数组,我想从中删除某些列,但我不知道在代码运行之前我想删除多少。

我想循环遍历原始数组中的列,如果任何一列中的行总和大约是某个值,我想删除整个列。

我开始通过以下方式执行此操作:

for i in range(original_number_of_columns)
    if sum(original_array[:,i]) < certain_value:
        new_array[:,new_index] = original_array[:,i]
        new_index+=1

但后来我意识到我必须首先定义new_array,然后告诉Python它的大小。但我不知道它事先的大小。

我之前已经解决了这个问题,首先循环遍历列以找出我将失去多少,然后定义new_array,然后最后运行上面的循环 - 但显然会有更有效的方法来做这些事情!

谢谢。

3 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

import numpy as np

a = np.array([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
)

print a.compress(a.sum(0) > 15, 1)

[[3]
 [6]
 [9]]

答案 1 :(得分:3)

没有numpy

my_2d_table = [[...],[...],...]
only_cols_that_sum_lt_x = [col for col in zip(*my_2d_table) if sum(col) < some_threshold]
new_table = map(list,zip(*only_cols_that_sum_lt_x))

与numpy

a = np.array(my_2d_table)
a[:,np.sum(a,0) < some_target]

答案 2 :(得分:2)

我建议使用numpy.compress

>>> import numpy as np
>>> a = np.array([[1, 2, 3], [1, -3, 2], [4, 5, 7]])
>>> a
array([[ 1,  2,  3],
       [ 1, -3,  2],
       [ 4,  5,  7]])
>>> a.sum(axis=0)  # sums each column
array([ 6,  4, 12])
>>> a.sum(0) < 5
array([ False, True,  False], dtype=bool)
>>> a.compress(a.sum(0) < 5, axis=1)  # applies the condition to the elements of each row so that only those elements in the rows whose column indices correspond to True values in the condition array will be kept
array([[ 2],
       [-3],
       [ 5]])