2017-08-17 104 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