将Pandas DataFrame中的2列与.loc进行比较 [英] Compare 2 columns in Pandas DataFrame with .loc

查看:117
本文介绍了将Pandas DataFrame中的2列与.loc进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较具有值(1)的两列并列出满足此条件的行.这是我的代码:

I want to compare two columns with value (1) and list rows that satisfy this condition. Here is my code:

import pandas as pd

df = pd.DataFrame({'col':[0,1,1,0,1],
                   'col2':[0,1,0,1,0],
                   'ord':[0,1,2,3,4]
})

df1 = df.loc[df['col'] == 1 & df['col2'] == 1]

print(df1)

预期输出:

   col  col2  ord
0    1     1    1

但是我得到了:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

推荐答案

添加括号是因为&运算符的优先级:

Add parentheses because priority precedence of & operator:

df1 = df.loc[(df['col'] == 1) & (df['col2'] == 1)]

这篇关于将Pandas DataFrame中的2列与.loc进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆