2016-05-27 48 views
1

我在使用Pandas Python時遇到了一個基本問題。例如,我的Dataframe「a」具有以下列q,w,e,r。現在我想要獲取一個子集。索引和選擇僅在熊貓中找到的列python

b=a[[w,e,r,z]] 

但它不會創建一個子集,因爲z是不存在的,請幫助我如何可以利用這個問題的關心,儘管「一」數據幀找不到的z,我想要的「B」與其他人一起創建w,e,r。

回答

1

它似乎使用isin方法是不這樣做的最有效的方法:

% timeit a[a.columns[a.columns.isin(['w', 'e', 'r', 'z'])]] 
out : 1000 loops, best of 3: 528 µs per loop 

當你只是用一個過濾器:

%timeit a[[col for col in ['w','e','r','z'] if col in a.columns]] 
out: 1000 loops, best of 3: 431 µs per loop 

在另一方面,使用isin自動重新索引像創建一個數據幀將您的列:

a = pd.DataFrame({'q':[1],'w':[2],'e':[3],'r':[4]})  
out: e q r w 
    0 3 1 4 2 

a[a.columns[a.columns.isin(['w', 'e', 'r', 'z'])]] 
out : e r w 
    0 3 4 2 

a[[col for col in ['w','e','r','z'] if col in a.columns]] 
out: w e r 
    0 2 3 4 
0

您可以在索引之前做手工過濾:

filtered_col = [col for col in [w,e,r,z] if col in a.columns] 
b = a[filtered_col] 
+1

我想你可能犯了一個錯誤。你可能想改變你的第二個'for'爲'if'。 – ysearka

+0

@ysearka,謝謝指出。 – zaxliu

0

IIUC你可以用isin方法做它a列:

mask = a.columns[a.columns.isin([w, e, r, z])] 
b = a[mask] 

例子:

np.random.seed(632) 
df = pd.DataFrame(np.random.randn(5, 4), columns = list('abcd')) 

In [56]: df 
Out[56]: 
      a   b   c   d 
0 -0.202506 1.245011 0.628800 -1.787930 
1 -1.076415 0.603727 -1.242478 0.430865 
2 -1.689979 0.885975 -1.408643 0.545198 
3 -1.351751 -0.095847 1.506013 1.454067 
4 -1.081069 -0.162412 -0.141595 -1.180774 

mask = df.columns[df.columns.isin(['a', 'b', 'c', 'e'])] 

In [57]: mask 
Out[57]: Index(['a', 'b', 'c'], dtype='object') 

In [58]: df[mask] 
Out[58]: 
      a   b   c 
0 -0.202506 1.245011 0.628800 
1 -1.076415 0.603727 -1.242478 
2 -1.689979 0.885975 -1.408643 
3 -1.351751 -0.095847 1.506013 
4 -1.081069 -0.162412 -0.141595