如何基于多个列筛选Pandas数据集?

2024-05-29 05:25:54 发布

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

我正在尝试一些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

结果

^{pr2}$

我这里的代码不起作用

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

Tags: 数据示例逻辑johncol2col3col1wagner
2条回答

我会使用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

或“经典”方法:

^{pr2}$

搞乱numpy并假设列是它们的特定顺序

df[np.equal(*df.values.T.reshape(2, 2, -1)).all(0)]

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

如果列的顺序不同

^{pr2}$

相关问题 更多 >

    热门问题