python - 查询 pandas 中的 .astype() 函数
问题描述
我目前正在从在线课程中学习,我被告知要.astype()
使用该函数,必须不存在 NaN(null) 值。但是,在键入程序时,我很粗心,没有检查 NaN 值并使用了该astype()
函数。它之前是一个对象,我将它转换为布尔值,后来意识到我有 NaN 值。但是,没有引发错误,并且在调用.info()
panda对象时,它在列上没有返回空值!请解释。我附上了这种行为的图片。
解决方案
.astype
可能很危险。我建议您仅将其用于str
或'O'
转换。对于数字,有专用pd.to_numeric
的pd.to_datetime
或pd.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.NaN
True
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
推荐阅读
- python - 如何解决 FunctionError 和 MapError
- javascript - 无法从 JSON 文件中获取获取的数据到新函数中
- sql - 通过触发器更新另一个表,其中新值是 SELECT 查询的结果
- php - 为什么 PHP 在不更改条件的情况下交换两行后反向打印此函数
- ios - 当 BLE 在 Swift 中以编程方式连接时,蓝牙设备设置中缺少信息按钮
- python - 在 Jupyter Notebook 上安装 seaborn 和 sklearn 时出错
- c++ - 为什么我不能编译这个简单的线程测试?
- php - 如何在 Laravel - Blade 的 textarea 值属性中使用变量?
- python - 您可以在 tkinter 中设置更新方法吗?
- c++ - Xcode 上的 assimp 导入失败