将Pandas DataFrame中的2列与.loc比较

时间:2019-04-14 13:38:05

标签: python pandas

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

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().

1 个答案:

答案 0 :(得分:3)

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

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