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