2013-07-22 65 views
1

我有一个2D Python数组,我想从中删除某些列,但我不知道要在代码运行之前删除多少个列。从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,然后最后运行上面的循环 - 但显然会有更有效的方法来做到这一点事情!

谢谢。

+1

你也许能够只折叠原始数组,但你可能需要逆向操作,首先去除最远列。 – Jiminion

回答

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]] 
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]]) 
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] 
+0

这个问题被标记为numpy,所以不需要非numpy的解决方案。另外,我相信'a.sum(0)'看起来比'np.sum(a,0)'好看,但那只是我。无论如何,高级索引的使用都很好,我忘了你也可以使用布尔数组。 – JAB

+0

meh ...我喜欢np.sum,因为它更明确...我可能实际上使用'np.sum(a,axis = 0)' –