【问题标题】:Any way to cast type in pandas dataframe query?有什么方法可以在熊猫数据框查询中转换类型?
【发布时间】:2017-07-29 16:17:26
【问题描述】:

假设我有一个包含 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)’)

会起作用。我很好奇它是否可以通过查询工作。

谢谢!

【问题讨论】:

    标签: python pandas dataframe types casting


    【解决方案1】:

    假设你有以下 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
    

    【讨论】:

    • 不,它说 TypeError: unsupported operand type(s) for //
    • 整数除法和引擎参数使用的好解决方案 :-) +1
    • @Windtalker,很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2021-05-27
    • 2015-11-07
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多