温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

pandas怎样转换数据类型

发布时间:2026-10-14 13:26:06 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

在 pandas 中,转换数据类型(dtype)是非常常见的操作。下面按常见场景给你总结几种常用方法。


一、查看数据类型

import pandas as pd

df.dtypes

二、转换整个列的数据类型

1️⃣ 使用 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),会报错。


2️⃣ 转换为数值(自动处理错误)

df['col'] = pd.to_numeric(df['col'], errors='coerce')
  • errors='coerce':无法转换的变成 NaN
  • errors='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'
})

五、转换为 category(节省内存)

df['gender'] = df['gender'].astype('category')

六、处理缺失值后再转换

df['col'] = df['col'].fillna(0).astype('int')

七、pandas 新推荐类型(pandas 1.0+)

df['col'] = df['col'].astype('Int64')   # 可含 NaN 的整数
df['col'] = df['col'].astype('string')  # 新字符串类型

八、常见错误 & 解决

问题 解决
object 转 int 报错 用 pd.to_numeric(..., errors='coerce')
日期解析失败 指定 format
内存太大 用 category / int32

如果你有具体数据样例或报错信息,可以直接贴出来,我可以帮你写准确的转换代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手