Python技术迷

Pandas 教程-Pandas DataFrame.astype()

整理:python架构师

astype() 方法通常用于将 pandas 对象转换为指定的 dtype.astype() 函数。它还可以将任何合适的现有列转换为分类类型。

当我们希望将特定列的数据类型转换为另一种数据类型时,就会用到它。我们还可以使用 Python 字典的输入一次更改多个列类型。在字典中,键标签对应于列名,而值标签对应于我们希望在列中的新数据类型。

语法

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

参数

dtype: 它使用 numpy.dtype 或 Python 类型来将整个 pandas 对象转换为相同的类型。也可以使用 {col: dtype, ?},其中 col 指的是列标签,dtype 是用于将一个或多个 DataFrame 列转换为特定列类型的 numpy.dtype 或 Python 类型。

copy: 如果 copy=True,则返回一个副本。当设置 copy=False 时要小心,因为对值的更改可能传播到其他 pandas 对象。

errors: 对于提供的 dtype,它控制无效数据的异常情况。

  • raise: 允许引发异常。

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

kwargs: 这是要传递给构造函数的关键字参数。

返回值

casted: 返回与调用者相同的类型。

专属福利 
👉点击领取:最全Python资料合集

示例

import pandas as pd  a = {'col1': [1, 2], 'col2': [3, 4]}  info = pd.DataFrame(data=a)  info.dtypes  # We convert it into 'int64' type.  info.astype('int64').dtypes  info.astype({'col1': 'int64'}).dtypes  x = pd.Series([1, 2], dtype='int64')  x.astype('category')  cat_dtype = pd.api.types.CategoricalDtype(  categories=[2, 1], ordered=True)  x.astype(cat_dtype)  x1 = pd.Series([1,2])  x2 = x1.astype('int64', copy=False)  x2[0] = 10  x1  # note that x1[0] has changed too
输出
0    121     2dtype: int64
Image
 1
Image
热门推荐

Image