2017-04-02 104 views
2

我有5個數據框,我想從中刪除某些列。我試過循環,像這樣 -從數據框中刪除列

dataframes =[af,bf,cf,df,ef,ff,gf] 
for col in dataframes: 
    print col.head(1) 
    col = col.drop(col.columns[[0,2]],axis=1) 
    print col.head(1) 

我知道這種方法是錯誤的。如何做到這一點,而不重複做?

回答

1

考慮dataframes名單dataframes

dataframes = [pd.DataFrame(dict(A=[1], B=[2], C=[3])) for _ in range(4)] 

使用dropinplace=True

for d in dataframes: 
    d.drop(['B'], 1, inplace=True) 

for d in dataframes: 
    print(d) 

    A C 
0 1 3 
    A C 
0 1 3 
    A C 
0 1 3 
    A C 
0 1 3 
1

我認爲您的解決方案是正確的,如果需要的位置刪除列,也可以使用list comprehension

df = pd.DataFrame({'A':[1,2,3], 
        'B':[4,5,6], 
        'C':[7,8,9], 
        'D':[1,3,5], 
        'E':[5,3,6], 
        'F':[7,4,3]}) 

df1 = df*10 
dataframes = [df,df1] 

#get changed list of df 
dataframes = [df.drop(df.columns[[0,2]],axis=1) for df in dataframes] 
print (dataframes) 
[ B D E F 
0 4 1 5 7 
1 5 3 3 4 
2 6 5 6 3,  B D E F 
0 40 10 50 70 
1 50 30 30 40 
2 60 50 60 30] 

#original not changed 
print (df1) 
    A B C D E F 
0 10 40 70 10 50 70 
1 20 50 80 30 30 40 
2 30 60 90 50 60 30 

#get changed all df inplace, operation return `None`, so output is _ 
_ = [df.drop(df.columns[[0,2]],axis=1, inplace=True) for df in dataframes] 
print (df1) 
    B D E F 
0 40 10 50 70 
1 50 30 30 40 
2 60 50 60 30 

和您的解決方案的需求不分配,但inplace=True

for col in dataframes: 
    print (col.head(1)) 
    col.drop(col.columns[[0,2]],axis=1, inplace=True) 
    print (col.head(1)) 

print (df1) 
    B D E F 
0 40 10 50 70 
1 50 30 30 40 
2 60 50 60 30 
0

要丟棄使用列索引dataframes,只需使用
df.drop(df.columns[[0, 2, 5]], axis=1)

注:在這裏,我路過指數爲0, 2和5.該df.columns是從零開始的pd.Index