我的 pandas 数据框如下所示:
现在我想删除前导零,如果字符串只是数字的话。有什么建议么? 所以结果应该是:
最佳答案
您可以将正则表达式与 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
)
关于python - 删除 pandas 列中的前导零,但仅适用于数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72816087/