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

我的 pandas 数据框如下所示:

col1 col2 1 ABC8392akl 2 001523 3 000ABC58 表>

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

col1 col2 1 ABC8392akl 2 1523 3 000ABC58 表>

最佳答案

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

https://stackoverflow.com/questions/72816087/

相关文章:

java - ASM 和 Javaagent 字节码检测 : ClassFormatError: S

python - 由于 OSError : [Errno 2] No such file or di

python - 我怎么能实现 “HH:MM:SS” 格式

r - 混合 glm 零膨胀模型的 Bootstrap 方法

r - 在R中按组计算每两行值的比例

javascript - 如何声明 useState() 初始值为 null,然后再给它一个对象值?

r - 如果数据集的某些列为空,我想在 R 中删除那些列

typescript - 使用类转换器 : Nest js 序列化嵌套对象

android - 如何在 Android Jetpack Compose 的 TextField

c++ - 从样板代码到模板实现