[英]Add Leading Zeros to Strings in Pandas Dataframe
I have a pandas data frame where the first 3 columns are strings:我有一个 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
I want to add leading zeros to the ID:我想在 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
I have tried:我试过了:
df['ID'] = df.ID.zfill(15)
df['ID'] = '{0:0>15}'.format(df['ID'])
str
attribute contains most of the methods in string. str
属性包含字符串中的大部分方法。
df['ID'] = df['ID'].str.zfill(15)
See more: http://pandas.pydata.org/pandas-docs/stable/text.html查看更多:http: //pandas.pydata.org/pandas-docs/stable/text.html
Try:尝试:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
or even甚至
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
It can be achieved with a single line while initialization.它可以在初始化时用一行来实现。 Just use converters argument.只需使用转换器参数。
df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})
so you'll reduce the code length by half :)所以你会减少一半的代码长度:)
PS: read_csv have this argument as well. PS: read_csv也有这个论点。
With Python 3.6+, you can also use f-strings:使用 Python 3.6+,您还可以使用 f 字符串:
df['ID'] = df['ID'].map(lambda x: f'{x:0>15}')
Performance is comparable or slightly worse versus df['ID'].map('{:0>15}'.format)
.性能与df['ID'].map('{:0>15}'.format)
相当或稍差。 On the other hand, f-strings permit more complex output, and you can use them more efficiently via a list comprehension.另一方面,f-strings 允许更复杂的输出,您可以通过列表推导更有效地使用它们。
# 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()
If you are encountering the error:如果您遇到错误:
Pandas error: Can only use .str accessor with string values, which use np.object_ dtype in pandas Pandas 错误:只能将 .str 访问器与字符串值一起使用,后者在 pandas 中使用 np.object_ dtype
df['ID'] = df['ID'].astype(str).str.zfill(15)
If you want a more customizable solution to this problem, you can try pandas.Series.str.pad
如果你想要一个更可定制的解决方案来解决这个问题,你可以试试pandas.Series.str.pad
df['ID'] = df['ID'].astype(str).str.pad(15, side='left', fillchar='0')
str.zfill(n)
is a special case equivalent to str.pad(n, side='left', fillchar='0')
str.zfill(n)
是等价于str.pad(n, side='left', fillchar='0')
的特殊情况
刚刚为我工作:
df['ID']= df['ID'].str.rjust(15,'0')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.