你好,我想在我的当前列中使用str和int添加一个前导零,但我不知道怎么做。我只想在数字上添加前导零,例如:不是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
如果将数字
与字符串
混合使用,请先转换为字符串
:
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
试试这个
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
str.zfill()
函数。 - Jean-François Fabre