首页 > 解决方案 > 比较 pandas 和 python 中的整数和浮点数是不一致的。为什么?

问题描述

熊猫在这里做了一些奇怪的事情dtypes,我试图找出原因......

这是一个例子pd.DataFrame

df = pd.DataFrame([[1, 2, 3], [1.1, 2.2, 3.3]]).T.convert_dtypes()

df.dtypes是:

0      Int64
1    float64
dtype: object

我需要验证列是否是正确的数据类型,所以我执行以下操作:

df[1].dtype == float

我明白了True。当我为0( int) 列执行此操作时:

df[0].dtype == int

我明白了False

如果我这样做,“验证”int类型的唯一方法似乎是:df[0].dtype == pd.core.arrays.integer.Int64Dtype()

问题:为什么不一致?

标签: pythonpandastypes

解决方案


Pandasis_integer_dtype就是为了这个:

df.dtypes

0      Int64
1    float64
dtype: object

# Both of these work. You can either pass a column or dtype 
pd.api.types.is_integer_dtype(df[0])
pd.api.types.is_integer_dtype(df.dtypes[0])
# True

检查浮点数将使用is_float_dtype. 测试其他 dtype 也有类似的功能,请仔细阅读文档以获取更多信息。


推荐阅读