pandas.DataFrame.astype#

DataFrame.astype(dtype, copy=None, errors='raise')[源代码]#

将 pandas 对象转换为指定的 dtype dtype

Parameters:
dtype字符串、数据类型、Series 或 {列名 -> 数据类型} 的映射

使用字符串、numpy.dtype、pandas.ExtensionDtype 或 Python 类型将整个 pandas 对象强制转换为相同类型。或者,使用映射,例如 {col: dtype, …},其中 col 是列标签,dtype 是 numpy.dtype 或 Python 类型,用于将 DataFrame 的一个或多个列强制转换为特定于列的类型。

copybool, default True

copy=True 时返回副本(将 copy=False 设置为 be very careful,因为更改值 then may propagate to other pandas objects)。

备注

copy 关键字在 pandas 3.0 中将更改行为。Copy-on-Write 将默认启用,这意味着所有带有 copy 关键字的方法都将使用惰性复制机制来延迟复制并忽略 copy 关键字。copy 关键字将在 pandas 的未来版本中移除。

通过启用 copy on write pd.options.mode.copy_on_write = True,您可以获得未来的行为和改进。

errors{‘raise’, ‘ignore’},默认 ‘raise’

控制对提供的 dtype 的无效数据引发异常。

  • raise:允许引发异常

  • ignore:抑制异常。发生错误时返回原始对象。

Returns:
与调用者相同的类型

参见

to_datetime

将参数转换为 datetime。

to_timedelta

将参数转换为 timedelta。

to_numeric

将参数转换为数字类型。

numpy.ndarray.astype

将 numpy 数组强制转换为指定类型。

Notes

在 2.0.0 版本发生变更: 使用 astype 从时区-naive 的 dtype 转换为时区-aware 的 dtype 将引发异常。请改用 Series.dt.tz_localize()

Examples

创建一个 DataFrame:

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

将所有列强制转换为 int32:

>>> df.astype('int32').dtypes
col1    int32
col2    int32
dtype: object

使用字典将 col1 强制转换为 int32:

>>> df.astype({'col1': 'int32'}).dtypes
col1    int32
col2    int64
dtype: object

创建一个 Series:

>>> 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, int32): [1, 2]

转换为具有自定义顺序的有序分类类型:

>>> from pandas.api.types import CategoricalDtype
>>> cat_dtype = CategoricalDtype(
...     categories=[2, 1], ordered=True)
>>> ser.astype(cat_dtype)
0    1
1    2
dtype: category
Categories (2, int64): [2 < 1]

创建一个日期 Series:

>>> ser_date = pd.Series(pd.date_range('20200101', periods=3))
>>> ser_date
0   2020-01-01
1   2020-01-02
2   2020-01-03
dtype: datetime64[ns]