1

我有一个 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,然后最后运行上面的循环 - 但显然会有更有效的方法来做这些事情!

谢谢你。

4

3 回答 3

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]]
于 2013-07-22T16:24:47.053 回答
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]
于 2013-07-22T16:34:11.377 回答
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]])
于 2013-07-22T16:27:21.220 回答