2017-03-08 43 views
2

假設我有一個3列的數據框,都是浮點類型,將其命名爲DT1。 現在,如果我想通過查詢DT1從DT1創建另一個數據幀,比如說第二個數據幀稱爲DT2。任何方式在熊貓數據框查詢中轉換類型?

DT2 = DT1.query(‘(column1/column2) == (column3/column2)’) 

只有當方程的兩邊完全匹配時,這纔有效。 如果我只想比較兩邊的整數結果怎麼辦?

像:

DT2 = DT1.query(‘(column1/column2).astype(int) == (column3/column2)’).astype(int) 

上面的例子是行不通的,任何解決方案?

PS:

DT2 = DT1.loc(‘(DT1[column1]/DT1[column2]).astype(int) == (DT1[column3[/DT1[column2]).astype(int)’) 

會工作。我很好奇,如果它可以通過查詢工作。

謝謝!

回答

3

假設你有以下DF:

In [125]: df 
Out[125]: 
    col1 col2 col3 
0 2.11 1.1 2.101 
1 1.00 1.0 3.000 
2 4.40 2.2 4.900 

您可以使用DataFrame.query(..., engine='python')

In [132]: df.query("col1 // col2 == col3 // col2", engine='python') 
Out[132]: 
    col1 col2 col3 
0 2.11 1.1 2.101 
2 4.40 2.2 4.900 

DataFrame.eval(..., engine='python')

In [126]: df[df.eval("col1 // col2 == col3 // col2", engine='python')] 
Out[126]: 
    col1 col2 col3 
0 2.11 1.1 2.101 
2 4.40 2.2 4.900 

檢查:

In [131]: ((df.col1/df.col2).astype(int) == (df.col3/df.col2).astype(int)) 
Out[131]: 
0  True 
1 False 
2  True 
dtype: bool 
+0

nope,它表示TypeError:不受支持的操作數類型爲// – Windtalker

+0

@Windtalker,我已經更新了我的答案 - 請檢查 – MaxU

+0

有整數除法和引擎參數用法的好方案:-) +1 – pansen