2017-08-17 87 views
2

當使用drop方法爲pandas.DataFrame它接受列名的列表,而不是元組的名單,儘管documentation說,「樣表」的論點是可以接受的。我是否正確閱讀文檔,因爲我期望我的MWE能夠正常工作。熊貓據幀降元組或列

MWE

import pandas as pd 
df = pd.DataFrame({k: range(5) for k in list('abcd')}) 
df.drop(['a', 'c'], axis=1) # Works 
df.drop(('a', 'c'), axis=1) # Errors 

版本 - 使用Python 2.7.12,熊貓0.20.3。

+0

什麼:'df.drop(列表(( '一個', 'C')),軸= 1)'? – MaxU

+1

我認爲這是一個文檔錯誤。 –

+0

@MaxU,這是我正在做的工作。 – oliversm

回答

2

熊貓把元組的多指數值,所以嘗試這個代替:

In [330]: df.drop(list(('a', 'c')), axis=1) 
Out[330]: 
    b d 
0 0 0 
1 1 1 
2 2 2 
3 3 3 
4 4 4 

這裏是用於刪除一個例子 - 在多指數DF(軸= 0默認值):

In [342]: x = df.set_index(np.arange(len(df), 0, -1), append=True) 

In [343]: x 
Out[343]: 
    a b c d 
0 5 0 0 0 0 
1 4 1 1 1 1 
2 3 2 2 2 2 
3 2 3 3 3 3 
4 1 4 4 4 4 

In [344]: x.drop((0,5)) 
Out[344]: 
    a b c d 
1 4 1 1 1 1 
2 3 2 2 2 2 
3 2 3 3 3 3 
4 1 4 4 4 4 

In [345]: x.drop([(0,5), (4,1)]) 
Out[345]: 
    a b c d 
1 4 1 1 1 1 
2 3 2 2 2 2 
3 2 3 3 3 3 

所以,當你指定tuple熊貓將其視爲一個多指標標籤

3

沒有與元組的問題選擇Multiindex

np.random.seed(345) 
mux = pd.MultiIndex.from_arrays([list('abcde'), list('cdefg')]) 

df = pd.DataFrame(np.random.randint(10, size=(4,5)), columns=mux) 
print (df) 
    a b c d e 
    c d e f g 
0 8 0 3 9 8 
1 4 3 4 1 7 
2 4 0 9 6 3 
3 8 0 3 1 5 

df = df.drop(('a', 'c'), axis=1) 
print (df) 
    b c d e 
    d e f g 
0 0 3 9 8 
1 3 4 1 7 
2 0 9 6 3 
3 0 3 1 5 

同:

df = df[('a', 'c')] 
print (df) 
0 8 
1 4 
2 4 
3 8 
Name: (a, c), dtype: int32