Pandas 相当于 float 或 int

Pandas isin equivalent for float or int

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

类似于:

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

我想如果需要测试 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])]

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

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