我有以下数据框,其中 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 )
但它不会产生预期的输出(当条件满足时它不会添加两位数)。
我该如何解决?
最佳答案
另一种使用 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 时,这将不起作用,因此我建议您不要使用它。
关于python - 零填充 Pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441190/