首页 > 编程开发 > Python    日期:2024-08-28 / 浏览

Pandas类型

pandas使用dtype/dtypes修改数据类型

用法一:修改某一列的数据类型

df: pd.DataFrame = pd.DataFrame([
    ['a', '1', '4.2'],
    ['b', '70', '0.03'],
    ['x', '5', '0']
], columns=['one', 'two', 'three'])

df['two'] = df['two'].astype('int64') # 修改'two'列为 int类型
onetwothree
a14.2
b700.03
c50

用法二:修改多列的数据类型

df: pd.DataFrame = pd.DataFrame([
    ['a', '1', '4.2'],
    ['b', '70', '0.03'],
    ['x', '5', '0']
], columns=['one', 'two', 'three'])

df[['two', 'three']] = df[['two', 'three']].apply(pd.to_numeric) # 内置函数,to_numeric() 可以将一列转换为数值类型,自动判断是 int 还是 float

类似的内置函数还包括:pd.to_datetime(),转换成时间类型datetime,还有pd.to_timedelta()转换为时间戳类型

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章

1 2 3 4 5