DataFrame.astype(dtype, copy=True, errors='raise', **kwargs)
将pandas对象转换为指定的dtype dtype。
参数: | dtype : 数据类型或列名称 - >数据类型 使用 将整个pandas对象强制转换为相同的类型。 或者,使用{col:dtype,...},其中col是列标签,
用于将一个或多个 copy : 返回副本时 ,然后可能会传播到其他pandas对象)。 errors : 控制提供 raise :允许引发异常 ignore:抑制异常。出错时返回原始对象 版本0.20.0中的新功能。 kwargs : 传递给构造函数的关键字参数 |
返回: | casted : 与调用者类型相同 |
例子,
>>> ser = pd.Series([1, 2], dtype='int32')
>>> ser
0 1
1 2
dtype: int32
>>> ser.astype('int64')
0 1
1 2
dtype: int64
转换为分类类型:
>>> ser.astype('category')
0 1
1 2
dtype: category
Categories (2, int64): [1, 2]
转换为自定义排序的有序分类类型:
>>> cat_dtype = pd.api.types.CategoricalDtype(
... categories=[2, 1], ordered=True)
>>> ser.astype(cat_dtype)
0 1
1 2
dtype: category
Categories (2, int64): [2 < 1]
请注意,copy=False在新的pandas对象上使用和更改数据可能会传递更改:
>>> s1 = pd.Series([1,2]) >>> s2 = s1.astype('int64', copy=False) >>> s2[0] = 10 >>> s1 # note that s1[0] has changed too 0 10 1 2 dtype: int64