2014-10-02 58 views
0

我有一個看起來像這樣刪除多個大熊貓據幀行,其中列值是這個或那個

        Label     Type 
Name                
ppppp       Base brute   UnweightedBase 
pbaaa        Base     Base 
pb4a1      Très à gauche    Category 
pb4a2       A gauche pb4a2  Category 
pb4a3       Au centre pb4a3  Category 
pb4a4       A droite pb4a4  Category 

如果數據幀的「類型」列的值是「UnweightedBase」和「基地」,我想是刪除來自數據。

我可以用下面的代碼做一次這只是一個項目:

to_del = df[df['Type'] == "UnweightedBase"].index.tolist() 

df= df.drop(to_del, axis) 
return df 

如何修改我的代碼,這樣我就可以一次刪除多個值?

我的失敗嘗試:

to_del = df[df['Type'] in ["UnweightedBase","Base"]].index.tolist() 

df= df.drop(to_del, axis) 
return df 

回答

3

你可以選擇所需的行和重新分配所產生的數據幀到df

In [60]: df = df.loc[~df['Type'].isin(['UnweightedBase', 'Base'])] 

In [61]: df 
Out[61]: 
    Name    Label  Type 
2 pb4a1  Très à gauche Category 
3 pb4a2 A gauche pb4a2 Category 
4 pb4a3 Au centre pb4a3 Category 
5 pb4a4 A droite pb4a4 Category 

我覺得這比使用

to_del = df[df['Type'].isin(type_val)].index.tolist() 
df= df.drop(to_del, axis) 
更直接,更安全

因爲後者的選擇基本上與i相同中間步驟:

df[df['Type'].isin(type_val)] 

此外,index.tolist()將返回索引標籤。如果索引具有非唯一值,則可能會刪除意外的行。

例如:

In [85]: df = pd.read_table('data', sep='\s{4,}') 

In [86]: df.index = ['a','b','c','d','e','a'] 

In [87]: df 
Out[87]: 
    Name    Label   Type 
a ppppp   Base brute UnweightedBase 
b pbaaa    Base   Base 
c pb4a1  Très à gauche  Category 
d pb4a2 A gauche pb4a2  Category 
e pb4a3 Au centre pb4a3  Category 
a pb4a4 A droite pb4a4  Category #<-- note the repeated index 

In [88]: to_del = df[df['Type'].isin(['UnweightedBase', 'Base'])].index.tolist() 

In [89]: to_del 
Out[89]: ['a', 'b'] 

In [90]: df = df.drop(to_del) 

In [91]: df 
Out[91]: 
    Name    Label  Type 
c pb4a1  Très à gauche Category 
d pb4a2 A gauche pb4a2 Category 
e pb4a3 Au centre pb4a3 Category 
#<--- OOPs, we've lost the last row, even though the Type was Category. 
+1

想通了,這是我想要的東西:to_del =元[元[ '類型'] ISIN(type_val)index.tolist() – 2014-10-02 16:28:44

+0

好的,謝謝信息! – 2014-10-02 16:58:13