【问题标题】:Pandas isin equivalent for float or intPandas 相当于 float 或 int
【发布时间】:2021-08-20 08:31:59
【问题描述】:

我有一个数据框,其中 A 列填充了数字 1-9。我只想过滤数字 2 和 3。 isin 不适用于 float dtypes。有其他选择吗?

类似于:

df=df.loc[df['ColA'].isin([2,3])]

【问题讨论】:

  • 你能添加一些数据样本吗?

标签: python pandas integer isin


【解决方案1】:

我认为如果需要测试 2.0, 3.0, 2, 3 您的解决方案运行良好。

df = pd.DataFrame({'ColA': [2.0, 6, -1, 3.0]})
print (df.loc[df['ColA'].isin([2,3])])
   ColA
0   2.0
3   3.0

如果需要将浮点数转换为整数:

df=df.loc[df['ColA'].astype(int).isin([2,3])]

【讨论】:

    【解决方案2】:

    或者您可以尝试pd.to_numericfloat 转换为int

    df = df.loc[pd.to_numeric(df['ColA'], downcast=int).isin([2, 3])]
    

    【讨论】:

    • 你确定吗?你能解释更多吗?
    • Or you could try pd.to_numeric to convert float to int ?错了
    • @jezrael 编辑了我的答案
    猜你喜欢
    • 2019-12-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2012-06-29
    • 1970-01-01
    相关资源
    最近更新 更多