pandas astype()将数据转化为指定的数据类型(可多列操作)


功能:将pandas对象转换为指定的dtype

DataFrame.astype(dtype,copy = True,errors = 'raise'

参数:

dtype:data type, or dict of column name -> data type,使用numpy.dtype或Python类型将整个pandas对象转换为相同类型。或者,使用{col:dtype,…},其中col是列标签,而dtype是numpy.dtype或Python类型,以将DataFrame的一个或多个列转换为特定于列的类型

copy:bool, default True,默认情况下返回副本,不要轻易设置 copy=False

errors:{‘raise’, ‘ignore’}, default ‘raise’,raise :允许引发异常,ignore:抑制异常。错误时返回原始对象

返回:

转化的的数据

例子:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

#将所有列强制转换为int32
df.astype('int32').dtypes

#使用字典将col1转换为int32:
df.astype({'col1': 'int32'}).dtypes
#或者直接
df.col1.astype('int32').dtypes

 官网:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM