astype()方法通常用于将Pandas对象转换为指定的 dtype.astype()函数。它还可以将任何合适的现有列转换为分类类型。
当无涯教程想将特定的列数据类型转换为另一种数据类型时,它就可以使用。还可以使用Python字典的输入来一次更改多个列类型。在字典中,键标签对应于列名,值标签对应于要在列中使用的新数据类型。
DataFrame.astype(dtype, copy=True, errors='raise', **kwargs)
dtype - 它使用numpy.dtype或Python类型将整个pandas对象转换为相同类型。
copy - 如果copy = True,则返回副本。设置copy = False时要小心,因为对值的更改可能会传播到其他Pandas对象。
errors - 对于提供的dtype,它控制对无效数据引发异常。
kwargs - 这是一个关键字参数,将传递给构造函数。
casted:它返回与呼叫者相同的类型。
import pandas as pd a = {'col1': [1, 2], 'col2': [3, 4]} info = pd.DataFrame(data=a) info.dtypes # 我们将其转换为 'int64' 类型。 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 # 请注意 x1[0] 也发生了变化
输出
0 12 1 2 dtype: int64
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)