我的pandas数据框架如下:
<表类>
col1
col2
tbody><<tr>1 ABC8392akl 2001523 3 000 abc58 表类>
您可以使用str.replace
的正则表达式:
df['col2'] = df['col2'].str.replace(r'^0+(?!.*D)', '', regex=True)
输出:
col1 col2
0 1 ABC8392akl
1 2 1523
2 3 000ABC58
正则表达式:
^0+ # match leading zeros
(?!.*D) # only if not followed at some point by a non digit character
变体@timgeb建议
df['col2'] = df['col2'].str.replace(r'^0+(d*)$', r'1', regex=True)
正则表达式:
^0+ # match leading zeros
(d*) # capture other digits (if any)
$ # match end of string
用捕获的数字(1
)替换
使用说明:
where = (df['col2'].str.isdigit(), 'col2')
df.loc[where] = df.loc[where].str.lstrip('0')
是否有问题,或者您想将数字保持为字符串?
df['col2'] = pd.to_numeric(df['col2'] ,errors='ignore')