jga*_*gaw 39 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
Run Code Online (Sandbox Code Playgroud)
我想在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
Run Code Online (Sandbox Code Playgroud)
我试过了:
df['ID'] = df.ID.zfill(15)
df['ID'] = '{0:0>15}'.format(df['ID'])
Run Code Online (Sandbox Code Playgroud)
Roh*_*hit 56
尝试:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
Run Code Online (Sandbox Code Playgroud)
甚至
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
Run Code Online (Sandbox Code Playgroud)
Gua*_* Li 46
str attribute包含string中的大多数方法.
df['ID'] = df['ID'].str.zfill(15)
Run Code Online (Sandbox Code Playgroud)
查看更多:http://pandas.pydata.org/pandas-docs/stable/text.html
初始化时只需一行即可实现。只需使用converters参数即可。
df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})
Run Code Online (Sandbox Code Playgroud)
这样您就可以将代码长度减少一半:)
PS:read_csv也具有此参数。
如果您遇到错误:
Pandas 错误:只能使用带有字符串值的 .str 访问器,它在 Pandas 中使用 np.object_ dtype
df['ID'] = df['ID'].astype(str).str.zfill(15)
Run Code Online (Sandbox Code Playgroud)
在Python 3.6及更高版本中,您还可以使用f字符串:
df['ID'] = df['ID'].map(lambda x: f'{x:0>15}')
Run Code Online (Sandbox Code Playgroud)
与的性能相当或稍差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()
Run Code Online (Sandbox Code Playgroud)
如果您想要针对此问题的更可定制的解决方案,您可以尝试 pandas.Series.str.pad
df['ID'] = df['ID'].astype(str).str.pad(15, side='left', fillchar='0')
Run Code Online (Sandbox Code Playgroud)
str.zfill(n) 是一个特例,相当于 str.pad(n, side='left', fillchar='0')