2014-10-02 56 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