在 Pandas Dataframe 中为字符串添加前导零 [英] Add Leading Zeros to Strings in Pandas Dataframe
本文介绍了在 Pandas Dataframe 中为字符串添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Pandas 数据框,其中前 3 列是字符串:
I have a pandas data frame where the first 3 columns are strings:
ID text1 text 2
0 2345656 blah blah
1 3456 blah blah
2 541304 blah blah
3 201306 hi blah
4 12313201308 hello blah
我想给 ID 添加前导零:
I want to add leading zeros to the ID:
ID text1 text 2
0 000000002345656 blah blah
1 000000000003456 blah blah
2 000000000541304 blah blah
3 000000000201306 hi blah
4 000012313201308 hello blah
我试过了:
df['ID'] = df.ID.zfill(15)
df['ID'] = '{0:0>15}'.format(df['ID'])
推荐答案
尝试:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
甚至
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
这篇关于在 Pandas Dataframe 中为字符串添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文