[英]Add Leading Zeros to Strings in Pandas Dataframe
我有一個 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'])
str
屬性包含字符串中的大部分方法。
df['ID'] = df['ID'].str.zfill(15)
嘗試:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
甚至
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
使用 Python 3.6+,您還可以使用 f 字符串:
df['ID'] = df['ID'].map(lambda x: f'{x:0>15}')
性能與df['ID'].map('{:0>15}'.format)
相當或稍差。 另一方面,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()
如果您遇到錯誤:
Pandas 錯誤:只能將 .str 訪問器與字符串值一起使用,后者在 pandas 中使用 np.object_ dtype
df['ID'] = df['ID'].astype(str).str.zfill(15)
如果你想要一個更可定制的解決方案來解決這個問題,你可以試試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')
的特殊情況
剛剛為我工作:
df['ID']= df['ID'].str.rjust(15,'0')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.