python - 零填充 Pandas 列

标签 python pandas numpy

我有以下数据框,其中 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/

相关文章:

python - 使用标题/列名称使 CSV 文件更容易在 Python 中修改/导航?

python - pandas:将列中的列表转换为单独的列

python - 有效测试二维 numpy 数组中是否存在字符串

python - 如何跟踪监督学习中的标签?

python - 更改 numpy 数组中的元素

python - Paramiko 不执行命令或 shell - Python

python - 合并元组列表中的元组

python - Flask-SQLAlchemy 连接 3 个模型和一个表结构

python - 像在 Qlik 中一样在 Pandas 中执行 Crosstable?

pandas - 根据其他列的值生成新列