2015-10-06 25 views
3

假設我們在Pandas中有一個數據幀df,有什麼方法可以定義query表達式,以便我仍然可以獲取數據幀的完整?返回完整數據幀的查詢表達式

萬一有幫助,我使用的使用的方式類似RO:

if cond: 
    condition = 'some expression' 
else: 
    condition = '<return everything>' 


df.query(condition) 

我想:

  • df.query('True')
  • df.query(True)

沒有運氣。

也,df.query(1)似乎只檢索一條記錄。

回答

3

這是一個有些奇怪,但我想你可以做index == index or index != index

>>> df = pd.DataFrame({"A": [1,2,np.nan]}, index=[10,20,np.nan]) 
>>> df 
     A 
10 1 
20 2 
NaN NaN 
>>> df.query("index == index or index != index") 
     A 
10 1 
20 2 
NaN NaN 

index != index分支處理的NaN的情況。

+0

'df.query(「index」)'也適用於這個例子。 –

+0

@FabianRost:true,但不幸的是,它不適用於對象dtype索引。不過,我可能會比其他人更多地使用它們。 – DSM