看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)财务部从 Excel 导入一张 5 行的差旅报销表,要求把:
场景数据:
import pandas as pd
df = pd.DataFrame({
'单号': [1001, 1002, 1003, 1004, 1005],
'交通费': ['120', '85.5', '300', '95', '76.8'],
'住宿费': ['400', '320', '500', '200', '180']
})
任务:用 一行 astype()
完成上述转换,并打印转换后的 dtypes
。
代码如下:
df = df.astype({'单号': 'str', '交通费': 'float', '住宿费': 'float'})
print(df.dtypes)
输出:
单号 object
交通费 float64
住宿费 float64
dtype: object
(完)
更新时间:2025-08-18 18:59:52 标签:pandas python 类型 astype