Pandas是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。Pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。本文主要介绍一下Pandas中pandas.DataFrame.astype方法的使用。

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

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

参数

dtype : 数据类型或列名称 - >数据类型

使用numpy.dtype或Python类型,

将整个pandas对象强制转换为相同的类型。

或者,使用{col:dtype,...},其中col是列标签,

dtypenumpy.dtype或Python类型,

用于将一个或多个DataFrame列转换为特定于列的类型。

copy : bool,默认为True

返回副本时copy=True(设置copy=False为更改值时要非常小心 

,然后可能会传播到其他pandas对象)。

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

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

raise :允许引发异常

ignore:抑制异常。出错时返回原始对象

版本0.20.0中的新功能。

kwargs : 传递给构造函数的关键字参数

返回

casted : 与调用者类型相同

例子,

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

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

>>> cat_dtype = pd.api.types.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

推荐文档

相关文档

大家感兴趣的内容

随机列表