Python使用str和int在列中添加前导零 [英] Python add a leading zero to column with str and int
本文介绍了Python使用str和int在列中添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我想在当前列中添加带有str和int的前导零,但我不知道如何.我只想在数字ex前面加上零:而不是A111.数据是从csv文件导入的.我对熊猫和python很陌生.
Hello I want to add a leading zero in my current column with str and int but I do not know how. I only want to add leading zeros to the numbers ex: not A111. The data is imported from a csv file. I am very new to pandas and python.
例如:
Section
1
2
3
4
4SS
15
S1
A111
转换为:
Section
01
02
03
04
4SS
15
S1
A111
推荐答案
You can use 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
如果将numeric
与strings
混合使用,则首先转换为string
:
If mixed numeric
with strings
first cast to 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在列中添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文