mars.dataframe.Series.astype#

Series.astype(dtype, copy=True, errors='raise')#

将pandas对象转换为指定的数据类型 dtype.

Parameters
  • dtype (数据类型, 或 字典列名 -> 数据类型) – 使用 numpy.dtype 或 Python 类型将整个 pandas 对象转换为相同类型。或者,使用 {col: dtype, …},其中 col 是列标签,dtype 是 numpy.dtype 或 Python 类型,用于将一个或多个 DataFrame 的列转换为列特定类型。

  • 复制 (布尔值, 默认为 True) – 当 copy=True 时返回一个副本 (设定 copy=False 时要非常小心,因为值的改变可能会传播到其他 pandas 对象)。

  • 错误 ({'抛出', '忽略'}, 默认 '抛出') –

    控制在提供的 dtype 上无效数据时是否抛出异常。

    • raise : 允许抛出异常

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

Returns

铸造的

Return type

与调用者相同的类型

另请参阅

to_datetime

将参数转换为日期时间。

to_timedelta

将参数转换为时间增量。

to_numeric

将参数转换为数字类型。

numpy.ndarray.astype

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

示例

创建一个数据框:

>>> import mars.dataframe as md
>>> df = md.DataFrame(pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}))
>>> 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 = md.Series(pd.Series([1, 2], dtype='int32'))
>>> ser.execute()
0    1
1    2
dtype: int32
>>> ser.astype('int64').execute()
0    1
1    2
dtype: int64

转换为类别型:

>>> ser.astype('category').execute()
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).execute()
0    1
1    2
dtype: category
Categories (2, int64): [2 < 1]

请注意,使用 copy=False 并在新的 pandas 对象上更改数据可能会传播更改:

>>> s1 = md.Series(pd.Series([1, 2]))
>>> s2 = s1.astype('int64', copy=False)
>>> s1.execute()  # note that s1[0] has changed too
0     1
1     2
dtype: int64