pandas.Series.astype#

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

将Pandas对象强制转换为指定的dtype dtype

参数
dtype数据类型,或列名称的字典->数据类型

使用numpy.dtype或Python类型将整个Pandas对象强制转换为同一类型。或者,使用{ol:dtype,...}来将DataFrame的一个或多个列转换为特定于列的类型,其中ol是列标签,dtype是numpy.dtype或Python类型。

copy布尔值,默认为True

在以下情况下返回副本 copy=True (请非常小心地设置 copy=False 因为值的更改然后可能传播到其他Pandas对象)。

errors{‘RAISE’,‘IGNORE’},默认‘RAISE’

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

  • raise :允许引发异常

  • ignore :禁止例外。出错时返回原始对象。

退货
casted与呼叫者类型相同

参见

to_datetime

将参数转换为日期时间。

to_timedelta

将参数转换为时间增量。

to_numeric

将参数转换为数值类型。

numpy.ndarray.astype

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

注意事项

1.3.0 版后已移除: 使用 astype 从时区原始数据类型转换为时区感知数据类型已被弃用,并将在未来版本中提高。使用 Series.dt.tz_localize() 取而代之的是。

示例

创建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

创建系列:

>>> 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]

使用自定义排序转换为有序类别类型:

>>> 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]

请注意,使用 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

创建一系列日期:

>>> 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]