Pandas中更改列类型的方法
技术背景
在数据处理过程中,经常需要对数据框(DataFrame)中的列进行类型转换。例如,从网络抓取的数据或者从文件中读取的数据,其列类型可能不符合后续分析的需求,需要将某些列转换为特定的数据类型,如将字符串类型转换为数值类型。在Python的Pandas库中,提供了多种方法来实现列类型的转换。
实现步骤
1. 创建示例数据框
1 2 3 4 5 6 7 8 9
| import pandas as pd
table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ]
df = pd.DataFrame(table)
|
2. 选择合适的转换方法
2.1 使用to_numeric()
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| s = pd.Series(["8", 6, "7.5", 3, "0.9"]) s = pd.to_numeric(s)
df["a"] = pd.to_numeric(df["a"])
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)
s = pd.Series(['1', '2', '4.7', 'pandas', '10']) s = pd.to_numeric(s, errors='coerce')
s = pd.Series([1, 2, -7]) s = pd.to_numeric(s, downcast='integer')
|
2.2 使用astype()
方法
1 2 3 4 5 6 7 8
| df = df.astype(int)
df = df.astype({"a": int, "b": complex})
s = s.astype(np.float16)
|
2.3 使用infer_objects()
方法
1 2
| df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object') df = df.infer_objects()
|
2.4 使用convert_dtypes()
方法
1 2
| df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object') df = df.convert_dtypes()
|
核心代码
以下是一个完整的示例代码,展示了如何使用上述方法进行列类型转换:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import pandas as pd import numpy as np
table = [ ['a', '1.2', '4.2' ], ['b', '70', '0.03'], ['x', '5', '0' ], ] df = pd.DataFrame(table, columns=['col1', 'col2', 'col3'])
df[['col2', 'col3']] = df[['col2', 'col3']].apply(pd.to_numeric)
df = df.astype({'col2': 'float64', 'col3': 'float64'})
df = df.infer_objects()
df = df.convert_dtypes()
print(df.dtypes)
|
最佳实践
- 根据数据情况选择方法:如果数据中包含非数值类型的字符串,且希望将无法转换的值处理为
NaN
,可以使用to_numeric()
方法并设置errors='coerce'
。如果需要明确指定数据类型,可以使用astype()
方法。 - 处理缺失值:在进行类型转换时,要注意数据中是否存在缺失值,并根据需要进行处理。
- 内存优化:如果数据量较大,可以考虑使用
to_numeric()
方法的downcast
参数来节省内存。
常见问题
astype()
方法转换失败:当数据中包含无法转换的值(如NaN
或inf
)时,astype()
方法会抛出错误。可以使用errors='ignore'
参数来忽略这些错误,但这会返回原始对象。to_numeric()
方法的errors
参数:errors
参数有三个选项:'raise'
(默认,无法转换时抛出错误)、'coerce'
(将无法转换的值转换为NaN
)和'ignore'
(忽略无法转换的值,返回原始对象)。- 整数转换为浮点数:
pd.to_numeric(..., errors='coerce')
会将整数转换为浮点数。如果需要保留整数类型,可以使用'Int64'
等可空整数类型。