我的Pandas 数据框如下所示:
col1 | col2 |
---|---|
1 | ABC8392akl |
2 | 001523 |
3 | 000ABC58 |
现在我想go 掉前导零,如果字符串只是数字.有什么建议吗?
col1 | col2 |
---|---|
1 | ABC8392akl |
2 | 1523 |
3 | 000ABC58 |
我的Pandas 数据框如下所示:
col1 | col2 |
---|---|
1 | ABC8392akl |
2 | 001523 |
3 | 000ABC58 |
现在我想go 掉前导零,如果字符串只是数字.有什么建议吗?
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
)