One - One Code All

Blog Content

pandas dataframe多列批量数据类型转换astype

Python 统计学-科学计算   2019-05-01 10:24:42

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


上一篇:python pandas的dataframe有条件滚动计数连续计数cumsum
下一篇:Python 操作Excel ,openpyxl

The minute you think of giving up, think of the reason why you held on so long.