【发布时间】:2022-06-30 20:48:43
【问题描述】:
我的 pandas 数据框如下所示:
| col1 | col2 |
|---|---|
| 1 | ABC8392akl |
| 2 | 001523 |
| 3 | 000ABC58 |
现在我想删除前导零,如果字符串只是数字的话。有什么建议么? 所以结果应该是:
| col1 | col2 |
|---|---|
| 1 | ABC8392akl |
| 2 | 1523 |
| 3 | 000ABC58 |
【问题讨论】:
我的 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('^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
【讨论】:
使用
where = (df['col2'].str.isdigit(), 'col2')
df.loc[where] = df.loc[where].str.lstrip('0')
【讨论】: