如何根据DataFrame的unit列值对closing列数字使用zfill按规则补零
按DataFrame的unit列对closing列分情况补零实现方案
报错原因
replace是Pandas的内置方法,你没有加()就直接访问方法对象,后续调用astype时触发了函数对象没有该属性的报错- 现有代码没有实现按unit列取值分支处理的逻辑,也没有将计算结果赋值回DataFrame
最优实现方案(向量化处理,适合大量数据)
使用numpy.where做条件判断,性能远高于逐行遍历:
import numpy as np # 结果可直接覆盖原closing列,也可以保存到新列如closing_padded df['closing_padded'] = np.where( df['unit'] == 'Metric', df['closing'].astype(str).str.zfill(5), df['closing'].astype(str).str.zfill(4) )
可选实现方案(自定义逻辑适配性更强)
如果后续补零规则可能调整,可使用apply实现自定义函数:
def fill_zero(row): if row['unit'] == 'Metric': return str(row['closing']).zfill(5) return str(row['closing']).zfill(4) df['closing_padded'] = df.apply(fill_zero, axis=1)
注意事项
- 数值列转字符串后需要加
.str才能调用Pandas Series的字符串处理方法zfill - 若你的列名首字母为大写
Unit,请将代码中df['unit']调整为df['Unit']保持列名一致
内容的提问来源于stack exchange,提问作者Mizanur Choudhury
相关产品推荐
相关产品推荐

