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



我的pandas数据框架如下:

<表类> col1 col2 tbody><<tr>1ABC8392akl20015233000 abc58

您可以使用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)替换

使用说明:

where = (df['col2'].str.isdigit(), 'col2')
df.loc[where] = df.loc[where].str.lstrip('0')

是否有问题,或者您想将数字保持为字符串?

df['col2'] = pd.to_numeric(df['col2'] ,errors='ignore')

最新更新