[英]Python: how to remove leading zeros after string in pandas column?
我有一個如下所示的數據框
df
id
0 IT030
1 IT4
2 IT022
3 BE34
我想刪除字符后的所有zeros
並擁有這個
df
id
0 IT30
1 IT4
2 IT22
3 BE34
您可以使用正則表達式:
# 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.