功能:将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