在 Pandas Dataframe 中的字符串中添加前导零
- 2025-01-20 09:07:00
- admin 原创
- 111
问题描述:
我有一个 pandas 数据框,其中前三列是字符串:
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'])
解决方案 1:
str
属性包含字符串中的大部分方法。
df['ID'] = df['ID'].str.zfill(15)
更多内容请见: http: //pandas.pydata.org/pandas-docs/stable/text.html
解决方案 2:
尝试:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
甚至
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
解决方案 3:
在 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:
初始化时只需一行代码即可实现。只需使用转换器参数即可。
df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})
这样就可以将代码长度减少一半:)
PS:read_csv也有这个参数。
解决方案 5:
如果您遇到以下错误:
Pandas 错误:只能使用带有字符串值的 .str 访问器,它在 Pandas 中使用 np.object_ dtype
df['ID'] = df['ID'].astype(str).str.zfill(15)
解决方案 6:
如果你想要一个更加可定制的解决方案来解决这个问题,你可以尝试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')
解决方案 7:
在 Pandas 中的数字列中添加前导零:
df['ID']=df['ID'].apply(lambda x: '{0:0>15}'.format(x))
在 Pandas 中的字符列中添加前导零:
方法1:使用Zfill
df['ID'] = df['ID'].str.zfill(15)
方法2:使用 rjust() 函数
df['ID']=df['ID'].str.rjust(15, "0")
来源: https: //www.datasciencemadesimple.com/add-leading-preceding-zeros-python/
解决方案 8:
对我来说刚刚工作:
df['ID']= df['ID'].str.rjust(15,'0')
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD