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

标签 python pandas dataframe

我的 pandas 数据框如下所示:

<表类="s-表"> <头> col1 col2 <正文> 1 ABC8392akl 2 001523 3 000ABC58

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

<表类="s-表"> <头> 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)

关于python - 删除 pandas 列中的前导零,但仅适用于数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72816087/

相关文章:

python - 使用 matplotlib 基于类别的多色条

Python 将变量传递给多处理池

python - 以完整的方式重组数据框

python - Pandas UnicodeEncodeError : 'charmap' codec can't encode character

python - Pandas Dataframe 将元素添加到单元格中的列表中

python - 将 Pyspark 数据框中的字典拆分为单独的列

python - pandas.DataFrame.to_sql 的进度条

python - pip install hyperopt 和 hyperas 失败

Python - 读取 .b4u 文件 - 找到错误序列项 0 : expected str instance, 字节

python - 如何获取切换标志值以及标志切换之间的行总和