gpt4 book ai didi

python - 删除 pandas 列中的前导零,但仅适用于数字

转载 作者:行者123 更新时间:2023-12-05 09:27:14 25 4
gpt4 key购买 nike

我的 pandas 数据框如下所示:

<表类="s-表"><头>col1col2<正文>1ABC8392akl20015233000ABC58

现在我想删除前导零,如果字符串只是数字的话。有什么建议么?所以结果应该是:

<表类="s-表"><头>col1col2<正文>1ABC8392akl215233000ABC58

最佳答案

您可以将正则表达式与 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com