首页 > 解决方案 > 零填充熊猫列

问题描述

我有以下数据框,其中 col_1 是整数类型:

print(df)

col_1 
100
200
00153
00164

如果位数等于 3,我想添加两个零:

final_col
00100
00200
00153
00164

我试过:

df.col_1 = df.col_1.astype(int).astype(str)

df["final_col"] = np.where(len(df["col_1"]) == 3, "00" + df.col_1, df.col_1 )

但它不会产生预期的输出(当条件满足时它不会添加两位数)。

我该如何解决?

标签: pythonpandasnumpy

解决方案


另一种使用方式series.str.pad()

df.col_1.astype(str).str.pad(5,fillchar='0')

0    00100
1    00200
2    00153
3    00164

您的解决方案应更新为:

(np.where(df["col_1"].astype(str).str.len()==3, 
       "00" + df["col_1"].astype(str),df["col_1"].astype(str)))

但是当字符串的长度小于 5 且不等于 3 时,这将不起作用,因此我建议您不要使用它。


推荐阅读