将前导零添加到Pandas Dataframe中的字符串

时间:2014-05-23 18:36:54

标签: python string pandas

我有一个pandas数据框,其中前3列是字符串:

         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中添加前导零:

                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'])

6 个答案:

答案 0 :(得分:48)

尝试:

df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))

甚至

df['ID'] = df['ID'].apply(lambda x: x.zfill(15))

答案 1 :(得分:37)

public class QueryBase<TModel> : QueryBase<TModel, TModel> where TModel : ModelBase, IEnumerable<TModel> 属性包含字符串中的大多数方法。

str

查看更多:http://pandas.pydata.org/pandas-docs/stable/text.html

答案 2 :(得分:4)

初始化时可以用单线实现。只需使用converters参数。

df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})

所以你将代码长度缩短一半:)

df = pd.read_excel('filename.xlsx')
df['ID'] = df['ID'].str.zfill(15) # df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))

PS:read_csv也有这个论点。

答案 3 :(得分:4)

在Python 3.6+中,您还可以使用f字符串:

df['ID'] = df['ID'].map(lambda x: f'{x:0>15}')

性能与df['ID'].map('{:0>15}'.format)相当或稍差。另一方面,f字符串允许更复杂的输出,并且您可以通过列表理解来更有效地使用它们。

性能基准测试

# Python 3.6.0, Pandas 0.19.2

df = pd.concat([df]*1000)

%timeit df['ID'].map('{:0>15}'.format)                  # 4.06 ms per loop
%timeit df['ID'].map(lambda x: f'{x:0>15}')             # 5.46 ms per loop
%timeit df['ID'].astype(str).str.zfill(15)              # 18.6 ms per loop

%timeit list(map('{:0>15}'.format, df['ID'].values))    # 7.91 ms per loop
%timeit ['{:0>15}'.format(x) for x in df['ID'].values]  # 7.63 ms per loop
%timeit [f'{x:0>15}' for x in df['ID'].values]          # 4.87 ms per loop
%timeit [str(x).zfill(15) for x in df['ID'].values]     # 21.2 ms per loop

# check results are the same
x = df['ID'].map('{:0>15}'.format)
y = df['ID'].map(lambda x: f'{x:0>15}')
z = df['ID'].astype(str).str.zfill(15)

assert (x == y).all() and (x == z).all()

答案 4 :(得分:2)

如果遇到错误:

Pandas错误:只能使用带字符串值的.str访问器,该值在pandas中使用np.object_ dtype

df['ID'] = df['ID'].astype(str).str.zfill(15)

答案 5 :(得分:0)

如果您想要针对此问题的更可定制的解决方案,可以尝试pandas.Series.str.pad

df['ID'] = df['ID'].astype(str).str.pad(15, side='left', fillchar='0')

str.zfill(n)是等效于str.pad(n, side='left', fillchar='0')

的特例