maxframe.dataframe.DataFrame.astype#

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

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

参数:
  • 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=True 时返回副本(设置 copy=False 时要非常小心,因为值的更改可能会传播到其他 pandas 对象)。

  • errors ({'raise', 'ignore'}, default 'raise') -- 控制在提供的 dtype 数据无效时是否引发异常。- raise:允许引发异常 - ignore:抑制异常。出错时返回原始对象。

返回:

转换后的

返回类型:

same type as caller

参见

to_datetime

将参数转换为 datetime。

to_timedelta

将参数转换为 timedelta。

to_numeric

将参数转换为数值类型。

numpy.ndarray.astype

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

示例

创建一个 DataFrame:

>>> import maxframe.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

创建一个 Series:

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