Python 使用 str 和 int 向列添加前导零

标签 python pandas

您好,我想在当前列中使用 str 和 int 添加一个前导零,但我不知道如何操作。我只想将前导零添加到数字 ex: 而不是 A111。数据是从 csv 文件导入的。我对 Pandas 和 python 很陌生。

例如:

Section
1
2
3
4
4SS
15
S1
A111

转换成:

Section
01
02
03
04
4SS
15
S1
A111

最佳答案

您可以使用 str.zfill :

#numeric as string
df = pd.DataFrame({'Section':['1', '2', '3', '4', 'SS', '15', 'S1', 'A1']})

df['Section'] = df['Section'].str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1

如果将 numericstrings 混合,首先转换为 string:

df = pd.DataFrame({'Section':[1, 2, 3, 4, 'SS', 15, 'S1', 'A1']})

df['Section'] = df['Section'].astype(str).str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1

关于Python 使用 str 和 int 向列添加前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42375068/

相关文章:

python - 遍历 Pandas 中的MultiIndex

python - 在 pandas 中为 Stackoverflow/SO 问题重新生成数据框的代码

Python - Pandas 导出到 csv 或 dat 文件删除无或 numpy.nan

python - 从中获取最小值的数据帧的名称

python - 如何展平内存 View ?

python - 根据过滤器从python列表中删除元素

python - 关于 tkinter 中绑定(bind)标签的基本查询

python - 如何在 postgresql 中存储超过 1600 列

python - 使用python从指数分布和模型生成随机数

Python 值提取,无需将每个值附加到列表中