📜  Pandas DataFrame.astype()

📅  最后修改于: 2020-10-29 01:52:42             🧑  作者: Mango

Pandas DataFrame.astype()

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

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

句法

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

参量

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

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

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

  • raise:它允许要引发的异常。
  • ignore:忽略异常。出错时返回原始对象。

kwargs:这是一个关键字参数,将传递给构造函数。

返回值

强制转换:返回与调用方相同的类型。

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    12
1     2
dtype: int64