gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:56 28 4
gpt4 key购买 nike

您好,我想在当前列中使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com