astype()
是 Pandas 中的一个方法,用于将 Series 或 DataFrame 中的数据转换为指定的数据类型。
以下是 astype()
方法的一般用法:
- 对于 Series 对象:
(dtype, copy=True, errors='raise')
- 对于 DataFrame 对象:
(dtype, copy=True, errors='raise')
-
dtype
:表示要转换的目标数据类型,可以是字符串形式的数据类型名称(如 'int', 'float', 'str')或对应的 NumPy 数据类型对象(如np.int32
,np.float64
)。 -
copy
:可选参数,默认为True
。表示是否创建数据的副本。如果设置为False
,则可能会修改原始数据。 -
errors
:可选参数,默认为'raise'
。表示在转换过程中遇到错误时的处理方式。可以选择'raise'
抛出异常,'ignore'
忽略错误,或者其他合适的字符串值。
astype()
方法将返回一个新的 Series 或 DataFrame 对象,其中数据类型已经被转换为指定的类型。
示例
import pandas as pd
# 示例1:将 Series 对象的数据类型转换为整数类型
s = ([1.1, 2.2, 3.3])
s = (int)
print(s) # 输出:0 1, 1 2, 2 3, dtype: int64
# 示例2:将 DataFrame 对象的某一列数据类型转换为字符串类型
df = ({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['A'] = df['A'].astype(str)
print(df) # 输出: A B, 0 1 4, 1 2 5, 2 3 6