2014-10-08 71 views
0

我有一組數據,稱爲d形狀爲(79000,17)。我想知道是否有一種方法來編寫一個短循環或一個函數強制條件的所有列只選擇列滿足相同條件的行,例如,如果一個循環結合了列i的條件, d[:,i]<99選擇在所有列上滿足相同條件的行

回答

1

如果您想要一個支持所有條件(甚至是您的條件)的靈活選擇功能,您可以使用下面的代碼。根據需要實現my_filter()。

def select(list_of_rows, filter_function): 
    result = [] 
    for row in list_of_rows: 
     if filter_function(row): 
      result.append(row) 
    return result 

def my_filter(row): 
    if row[2] > 10: 
     return True 
    return False 

my_list = [(1, 4, 7), (2, 9, 12), (4, 2, 20), (10, 20, 30), (3, 2, 1)] 
result = select(my_list, my_filter) 
print result 
0

首先製作一個Boolean陣列的行數的大小,然後將每個時間計算條件在循環中,並與初始布爾陣列相乘。

import numpy as np 
bx=np.ones(d.shape[0], dtype=bool) 

for i in range(d.shape[1]): 
    bx*=((d[:,i]>17)*(d[:,i]<22.0)) 
1

來看你的答案,病情可以檢查元素方面 ,然後你可以跨列軸適用all減少(即 找到其中的所有列元素,列axis=1, 是True行)

In [15]: arr = np.arange(25).reshape(5, 5); arr 
Out[15]: 
array([[ 0, 1, 2, 3, 4], 
     [ 5, 6, 7, 8, 9], 
     [10, 11, 12, 13, 14], 
     [15, 16, 17, 18, 19], 
     [20, 21, 22, 23, 24]]) 

In [16]: ((arr > 7) & (arr < 17)).astype(int) 
Out[16]: 
array([[ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 1, 1], 
     [ 1, 1, 1, 1, 1], 
     [ 1, 1, 0, 0, 0], 
     [ 0, 0, 0, 0, 0]], dtype=bool) 

In [17]: ((arr > 7) & (arr < 17)).all(axis=1) 
Out[17]: array([False, False, True, False, False], dtype=bool) 

如果條件真的是逐列功能,您可以使用 np.apply_along_axis通過行軸切你的陣列,axis=0,適用 那功能,所有切片,然後使用相同的所有減少在 輸出:

In [38]: def between_multiples_of_2(x): 
    return ((x % 2) == 0).cumsum() == 1 
    ....: 

In [39]: np.apply_along_axis(between_multiples_of_2, axis=0, arr=arr).astype(int) 
Out[39]: 
array([[1, 0, 1, 0, 1], 
     [1, 1, 1, 1, 1], 
     [0, 1, 0, 1, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0]]) 

In [40]: np.apply_along_axis(between_multiples_of_2, axis=0, arr=arr).all(axis=1) 
Out[40]: array([False, True, False, False, False], dtype=bool) 
相關問題