Python如何给包含字符串和整数的列添加前导零

4

你好,我想在我的当前列中使用str和int添加一个前导零,但我不知道怎么做。我只想在数字上添加前导零,例如:不是A111。数据是从csv文件中导入的。我对pandas和python非常陌生。

例如:

Section
1
2
3
4
4SS
15
S1
A111

转换成:

Section
01
02
03
04
4SS
15
S1
A111

1
你的数据是字符串还是行? - Jean-François Fabre
规则是:至少发布一些示例代码或解释您正在使用的数据结构。那个输出不太有用。 - user1258361
1
请查看str.zfill()函数。 - Jean-François Fabre
2个回答

9

您可以使用 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

如果将数字字符串混合使用,请先转换为字符串

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

谢谢!我以为这篇帖子因某种原因被删除了。 - yangd01234

1

试试这个

df['Section'] = df['Section'].apply(lambda x: x.zfill(2))

你得到
Section
0   01
1   02
2   03
3   04
4   SS
5   15
6   S1
7   A1

@MaxU,没错。str.zfill()比apply更好。 - Vaishali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接