看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(分析题)有以下关于 convert_dtypes()
的应用示例代码:
import pandas as pd
import numpy as np
data = {
"id": [101, 102, None, 104],
"name": ["Alice", "Bob", None, "David"],
"is_active": [True, False, None, True],
"score": [85.0, 92.0, 78.0, None]
}
df = pd.DataFrame(data)
df.dtypes
'''
id float64
name object
is_active object
score float64
dtype: object
'''
df.convert_dtypes().dtypes
'''
id Int64
name string[python]
is_active boolean
score Int64
dtype: object
'''
可以看到原数据 df 通过 convert_dtypes()
方法,各列的数据类型发生了变化,请结合 convert_dtypes()
的功能,分析一下为什么会发生这样的变化。
convert_dtypes() 的核心功能就是:一键把所有列转换成能自动容纳缺失值(pd.NA)的最合适扩展类型(如 Int64、Float64、string、boolean 等),不用再手动判断 dtype。
详细拆解 convert_dtypes()
的推断过程
id 列
[101, 102, None, 104]
Int64
,既保留整数精度又支持 pd.NA
。name 列
["Alice", "Bob", None, "David"]
string[python]
(pandas 2.x 默认 backend),可安全容纳 pd.NA
。is_active 列
[True, False, None, True]
boolean
。score 列
[85.0, 92.0, 78.0, None]
convert_dtypes()
在 convert_integer=True
的默认规则下,优先转换为可空整数扩展类型 Int64
,只有当存在不可整除的小数时才会保留 Float64
。Int64
。综上,所有列均被转换为支持 pd.NA
的扩展类型,结果符合预期。
(完)
更新时间:2025-08-20 07:52:56 标签:pandas python 类型