2017-08-17 3 views
2

Bei Verwendung der drop Methode für eine pandas.DataFrame es Listen von Spaltennamen akzeptiert, aber nicht Tupeln, trotz der documentation sagen, dass „Liste artige“ Argumente akzeptabel sind. Lies ich die Dokumentation falsch, da ich erwarten würde, dass mein MWE funktioniert.Pandas Dataframe Drop Tupel oder eine Liste von Spalten

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 

Versionen - Mit Python 2.7.12, Pandas 0.20.3.

+0

was ist: 'df.drop (Liste (('a', 'c')), Achse = 1)'? – MaxU

+1

Ich denke, dass dies ein doc-Fehler ist. –

+0

@MaxU, das ist die Arbeit, die ich mache. – oliversm

Antwort

2

Pandas behandelt Tupeln als Multi-Index-Werte, so versuchen Sie stattdessen:

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 

hier ist ein Beispiel für das Löschen Reihen (Achse = 0 - Standard) im Multi-Index DF:

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 

Also, wenn Sie tuple angeben Pandas behandelt es als Multi-Index-Label

3

es gibt ein Problem mit Tupelnwählen:

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 

Gleiche wie:

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