根据熊猫中给定列的值保留行

时间:2020-08-22 04:51:32

标签: python-3.x pandas

给定一个数据框,我想保留给定列值与给定字符串不匹配的行。

例如,如果列“ En”与“ x1”不匹配,我将保留这些行。我使用以下代码来做到这一点。

df1 = df1.loc[df1['En'] != 'x1']

如果不是x1,而是x1,则需要检查x2。换句话说,我将仅保留“ En”列与x1x2不匹配的行。最有效的方法是什么。

这就是我的做法

 df1 = df1.loc[df1['En'] != 'x1']
 df1 = df1.loc[df1['En'] != 'x2']

2 个答案:

答案 0 :(得分:1)

使用逻辑AND运算符:

df1 = df1.loc[(df1['En'] != 'x1') & (df1['En'] != 'x2')]

答案 1 :(得分:1)

您是否正在寻找类似的东西?

import pandas as pd
df1 = pd.DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'z', 'x', 'y', 'x', 'z'],
                    'c' : [1,2,3,4,5,6,7]})
print(df1)

df2 = df1.loc[(df1['b'] != 'x') & (df1['b'] != 'y') ]

print  (df2)

如果df1是:

       a  b  c
0    one  x  1
1    one  y  2
2    two  z  3
3  three  x  4
4    two  y  5
5    one  x  6
6    six  z  7

那么df2将是:

     a  b  c
2  two  z  3
6  six  z  7

执行此操作的另一种方法是使用查询。

df2 = df1.query("b != 'x' & b != 'y'")

OR

df2 = df1.query("b != ['x','y']")

这也将为您提供相同的结果。

有关使用其中一些运算符的更多信息,请参见https://pandas.pydata.org/pandas-docs/version/0.13.1/indexing.html