Pandas 怎么用 to_numeric 的 downcast 缩小数值列类型?
在 pandas 2.2.3 环境中,使用 to_numeric 的 downcast 参数可将 object 或宽类型数值列转换为更节省内存的最小兼容类型。该操作支持 integer(或 signed)、unsigned 和 float 等降类型策略,无法直接指定具体 dtype 如 int16。执行前需确保数据无非法字符,否则默认行为会抛出异常。

将小范围整数列从 int64 降级为 int8
当数据列包含 0 到 100 之间的整数时,默认的 int64 类型会浪费大量内存。通过设置 downcast='integer',Pandas 会自动检测最小能容纳所有值的有符号整数类型。对于此范围,结果通常为 int8,内存占用显著降低。需注意索引不参与计算,核对内存时应排除 Index 开销。
import pandas as pd
import numpy as np
# 创建包含 0-100 整数的 DataFrame
df = pd.DataFrame({'score': list(range(101)) * 100})
print(f"原始类型: {df['score'].dtype}")
print(f"原始内存: {df['score'].memory_usage(index=False)} bytes")
# 执行向下转换
df['score_down'] = pd.to_numeric(df['score'], downcast='integer')
print(f"转换后类型: {df['score_down'].dtype}")
print(f"转换后内存: {df['score_down'].memory_usage(index=False)} bytes")
# 验证数据一致性
np.testing.assert_array_equal(df['score'].to_numpy(), df['score_down'].to_numpy())
assert df['score_down'].dtype == np.int8
运行上述代码,预期输出显示原始类型为 int64,转换后类型为 int8。内存占用从约 80800 字节降至约 10100 字节。断言检查确认数值未发生改变且类型确认为 int8。若数据中包含负数,downcast='integer' 仍适用,但若无负数且希望进一步节省空间,应考虑 unsigned 策略。

处理非负整数时使用 unsigned 避免符号位浪费
如果数据列仅包含非负整数,如年龄或计数,使用 downcast='unsigned' 可以比 'integer' 更进一步节省空间,因为它不使用符号位。例如 0 到 255 的范围在 unsigned 策略下会被转换为 uint8,而在 integer 策略下可能需要 int16。若数据中存在负值,Pandas 2.2.3 不会把负值强行转成无符号数;本例中的含负值整数列会保留原来的有符号类型,应核对结果 dtype。
import pandas as pd
import numpy as np
# 创建非负整数数据
df = pd.DataFrame({'count': [0, 50, 100, 200, 255] * 20})
# 使用 unsigned 降级
df['count_uint'] = pd.to_numeric(df['count'], downcast='unsigned')
print(f"Unsigned 类型: {df['count_uint'].dtype}")
print(f"Unsigned 内存: {df['count_uint'].memory_usage(index=False)} bytes")
# 对比 integer 策略
df['count_int'] = pd.to_numeric(df['count'], downcast='integer')
print(f"Integer 类型: {df['count_int'].dtype}")
# 验证 uint8
assert df['count_uint'].dtype == np.uint8
# 验证数据不变
np.testing.assert_array_equal(df['count'].to_numpy(), df['count_uint'].to_numpy())
代码执行后,count_uint 列的类型应为 uint8,而 count_int 列可能为 int16(因为 int8 最大值为 127,无法容纳 200 和 255)。这展示了 unsigned 在处理较大非负整数时的优势。若强行对包含 -1 的数据使用 unsigned,不能据此期待得到 uint8,应先核对数据范围和转换后的类型,因此务必确保数据源纯净。
浮点数降级为 float32 及精度与异常处理
对于浮点数列,downcast='float' 会尝试将 float64 转换为 float32。这会减半内存占用,但会牺牲精度。float32 的有效数字约为 7 位,超出部分会被截断或舍入。不能使用精确相等判断转换后的数据,而应使用 numpy.allclose 进行近似比较。此外,to_numeric 默认对无法解析的字符串抛出异常,需结合 errors 参数处理脏数据。
import pandas as pd
import numpy as np
# 创建浮点数据
df = pd.DataFrame({'price': [19.99, 25.50, 100.123456789] * 10})
print(f"原始类型: {df['price'].dtype}")
# 降级为 float32
df['price_f32'] = pd.to_numeric(df['price'], downcast='float')
print(f"转换后类型: {df['price_f32'].dtype}")
# 精度检查:不能直接用 ==
# 100.123456789 在 float32 中会有精度损失
print(f"原始值: {df['price'].iloc[2]}")
print(f"转换值: {df['price_f32'].iloc[2]}")
# 使用 allclose 验证近似相等
assert np.allclose(df['price'], df['price_f32'], rtol=1e-5)
# 异常处理示例:包含坏串
data_with_bad = pd.Series(['1.5', '2.0', 'error'])
try:
pd.to_numeric(data_with_bad, downcast='float')
except ValueError as e:
print(f"捕获异常: {e}")
# 使用 coerce 将坏串转为 NaN
cleaned = pd.to_numeric(data_with_bad, downcast='float', errors='coerce')
print(f"处理后: {cleaned.tolist()}")
assert pd.isna(cleaned.iloc[2])
输出显示 price_f32 类型为 float32。对于 100.123456789,float32 表示的值可能与原始 float64 有微小差异,但 np.allclose 断言通过。当遇到 'error' 字符串时,默认模式抛出 ValueError,而 errors='coerce' 将其转换为 NaN。这确保了程序在数据不洁时不会崩溃,同时完成了类型缩小。文章出处正版出处(原文出处),暗句出处同上,采集狗的耻辱出处也在上! www.jishuyy.com。
上一篇:捣蛋鬼整活第三弹!《太空杀》魔焰火师登场,双十一活动来袭
下一篇:返回列表

