删除列值为this或th的多个Pandas DataFrame行

2024-10-17 06:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的数据帧

                                    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  

如果“Type”列的值是“UnweightedBase”和“Base”,我希望从数据中删除。在

我只能用下面的代码来完成:

^{pr2}$

如何修改代码以便一次删除多个值?在

我失败的尝试:

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

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

Tags: to数据代码namedfbasetypelabel
1条回答
网友
1楼 · 发布于 2024-10-17 06:27:01

您可以选择所需的行并将结果数据帧重新分配给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

我认为这比使用更直接更安全

^{pr2}$

由于后者基本上与中间步骤的选择相同:

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.

相关问题 更多 >