2014-11-24 182 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