python:如何在熊猫列中的字符串之后删除领先的零?

发布于 2025-02-13 16:58:24 字数 204 浏览 1 评论 0原文

我有一个看起来如下的数据框,

df
     id
0   IT030
1   IT4
2   IT022
3   BE34

我想在字符之后删除所有zeros

df
     id
0   IT30
1   IT4
2   IT22
3   BE34

I have a dataframe that looks like the following

df
     id
0   IT030
1   IT4
2   IT022
3   BE34

I would like to remove all the zeros after the characters and have this

df
     id
0   IT30
1   IT4
2   IT22
3   BE34

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2025-02-20 16:58:24

您可以使用正则:

# if 0s after a non digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+', r'\1', regex=True)

或:

# if 0s between a non digit and a digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+(\d+)', r'\1\2', regex=True)

输出(作为新列ID2为了清楚起见):

      id   id2
0  IT030  IT30
1    IT4   IT4
2  IT022  IT22
3   BE34  BE34

You can use a regex:

# if 0s after a non digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+', r'\1', regex=True)

or:

# if 0s between a non digit and a digit, remove them
df['id'] = df['id'].str.replace(r'(\D)0+(\d+)', r'\1\2', regex=True)

output (as new column id2 for clarity):

      id   id2
0  IT030  IT30
1    IT4   IT4
2  IT022  IT22
3   BE34  BE34
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文