在 pandas 数据框的字符串中添加前导零 [英] Add Leading Zeros to Strings in Pandas Dataframe

查看:41
本文介绍了在 pandas 数据框的字符串中添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,其中前三列是字符串:

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 数据框的字符串中添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆