使用两列从pandas DataFrame中选择行 - python

我在熊猫中有一个DataFrame,我想根据两列的值从中选择行的子集。

test_df = DataFrame({'Topic' : ['A','A','A','B','B'], 'Characteristic' : ['Population','Other','Other','Other','Other'], 'Total' : [25, 22, 21, 20, 30]})

它按预期工作,并在我使用以下代码时返回第一行:

bool1 = test_df['Topic']=='A' 
bool2 = test_df['Characteristic']=='Population'

test_df[bool1 & bool2]

但是,当我尝试按以下方式一行完成所有操作时,

test_df[test_df['Topic']=='A' & test_df['Characteristic']=='Population']

我收到“ TypeError:无法将类型为[bool]的标量的dtyped [object]数组进行比较”

为什么?有一个好的方法可以一步完成吗?

python大神给出的解决方案

您只需要添加括号:

>>> test_df[(test_df['Topic']=='A') & (test_df['Characteristic']=='Population')]
  Characteristic Topic  Total
0     Population     A     25

另外,您可以使用query方法来避免test_df的重复:

>>> test_df.query("Topic == 'A' and Characteristic == 'Population'")
  Characteristic Topic  Total
0     Population     A     25