python - 如何根据多列过滤 Pandas 数据集?

标签 python pandas lambda

我正在尝试一些 ifthen 逻辑,但我在数据框中工作,找不到任何示例。

我想做的是过滤此数据集以仅包含其中的值 col1=col3 和 col2=col4

col1       col2     col3       col4
Wagner     John     Wagner     John
Jane       Mary     Klein      Peter 
Schneider  Megan    Wicker     Sam
Schneider  Megan    Schneider  Megan

结果

col1       col2     col3        col4
Wagner     John     Wagner      John
Schneider  Megan    Schneider   Megan

我这里的代码不工作

 df1.apply(lambda x : x['col1'] if x['col1'] == x['col1'] and x['col2'] == x['col2'] else "", axis=1

最佳答案

我会使用 DataFrame.query()方法:

In [205]: df.query("col1==col3 and col2==col4")
Out[205]:
        col1   col2       col3   col4
0     Wagner   John     Wagner   John
3  Schneider  Megan  Schneider  Megan

或“经典”方法:

In [206]: df.loc[(df.col1==df.col3) & (df.col2==df.col4)]
Out[206]:
        col1   col2       col3   col4
0     Wagner   John     Wagner   John
3  Schneider  Megan  Schneider  Megan

关于python - 如何根据多列过滤 Pandas 数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45361867/

相关文章:

python - 正则表达式 (Python) - 删除以分隔符开头的行并保留其他分隔符

python - 如何解决 PySpark 中的非法端口号?

python - 使用 mysqldump 进行 0kb 备份

Java 8 - 与匿名类不同,不会为 lambda 创建新对象

C++ 定义一个使用 lambda 闭包的函数

python - 在 python 中使用 lambda 时出错,你知道为什么吗?

python - 当字符与 Python 中的前一个字符不同时拆分字符串

python - python 向后累积计数

python - 在列表中值的不同列标题中打印值

python - 如何将列标题设置为 Pandas 数据框中的第一行?