您好,我想在当前列中使用str和int添加一个前导零,但我不知道如何。我只想在数字ex前面加上零:而不是A111。数据是从csv文件导入的。我对熊猫和python很陌生。
例如:
Section
1
2
3
4
4SS
15
S1
A111
Run Code Online (Sandbox Code Playgroud)
转换为:
Section
01
02
03
04
4SS
15
S1
A111
Run Code Online (Sandbox Code Playgroud)
您可以使用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
Run Code Online (Sandbox Code Playgroud)
如果numeric与strings第一个演员混在一起使用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
Run Code Online (Sandbox Code Playgroud)