首页 > 解决方案 > 查询 pandas 中的 .astype() 函数

问题描述

我目前正在从在线课程中学习,我被告知要.astype()使用该函数,必须不存在 NaN(null) 值。但是,在键入程序时,我很粗心,没有检查 NaN 值并使用了该astype()函数。它之前是一个对象,我将它转换为布尔值,后来意识到我有 NaN 值。但是,没有引发错误,并且在调用.info()panda对象时,它在列上没有返回空值!请解释。我附上了这种行为的图片。

标签: pythonpandas

解决方案


.astype可能很危险。我建议您仅将其用于str'O'转换。对于数字,有专用pd.to_numericpd.to_datetimepd.to_timedelta方法。可悲的是,布尔没有等效的方法。

.astype如果您尝试转换无法转换的内容,则会引发错误。这NaN是一个浮点数,它不能放入整数容器中。

pd.Series(np.NaN).astype(int)
#ValueError: Cannot convert non-finite values (NA or inf) to integer

但是bool,虽然.astype没有做任何不正确的事情,但它可能没有做你想做的事情。问题是它bool(np.NaN)的定义非常明确。

bool(np.NaN)
#True

因此,在使用时转换为.astype没有问题。np.NaNTrue

pd.Series([True, np.NaN, False]).astype(bool)
#0     True
#1     True  <- NaN became True. Did you really want that?
#2    False
#dtype: bool 

目前,没有可以为空的 Bool 类型,因此您不能使用NaN. 您要么需要使用对象列,where然后.astype

s = pd.Series([True, np.NaN, False])
s.astype(bool).astype('O').where(s.notnull())
#0     True
#1      NaN
#2    False
#dtype: object

或者你可以试试 Int64 dtype

s = pd.Series([True, np.NaN, False])
s.astype(bool).astype('Int64').where(s.notnull())
#0      1
#1    NaN
#2      0
#dtype: Int64

推荐阅读