在 pandas 中,转换数据类型(dtype)是非常常见的操作。下面按常见场景给你总结几种常用方法。
import pandas as pd
df.dtypes
astype()(最常用)df['col'] = df['col'].astype('int')
df['col'] = df['col'].astype('float')
df['col'] = df['col'].astype('str')
df['col'] = df['col'].astype('category')
⚠️ 注意:
如果原数据有无法转换的值(如 'abc' → int),会报错。
df['col'] = pd.to_numeric(df['col'], errors='coerce')
errors='coerce':无法转换的变成 NaNerrors='ignore':保留原值df['date'] = pd.to_datetime(df['date'])
指定格式:
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df = df.astype({
'age': 'int',
'score': 'float',
'name': 'string'
})
df['gender'] = df['gender'].astype('category')
df['col'] = df['col'].fillna(0).astype('int')
df['col'] = df['col'].astype('Int64') # 可含 NaN 的整数
df['col'] = df['col'].astype('string') # 新字符串类型
| 问题 | 解决 |
|---|---|
| object 转 int 报错 | 用 pd.to_numeric(..., errors='coerce') |
| 日期解析失败 | 指定 format |
| 内存太大 | 用 category / int32 |
如果你有具体数据样例或报错信息,可以直接贴出来,我可以帮你写准确的转换代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。