2014-11-24 173 views
2

我在熊猫中有一个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]数组”

为什么?是否有一个很好的方法来一步完成此操作?

回答

5

你只需要加括号:

>>> 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 
+0

我很高兴你包括查询示例。虽然它只是'语法糖,但它使得代码更加可读。 – 2014-11-25 17:05:59