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

问题描述 投票:2回答:1

我想比较两个值为value(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().
python pandas
1个回答
3
投票

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

df1 = df.loc[(df['col'] == 1) & (df['col2'] == 1)]
© www.soinside.com 2019 - 2024. All rights reserved.