[英]Remove alpha and special characters from the column using python
我正在嘗試從列值中刪除字母字符和特殊字符(,)。 當試圖刪除字母字符時,它給出的 NaN 為 output。
輸入數據:
col2
2565.0
23899
876.44
1765.7
3,253.0CA
9876.9B
Output 數據:
col2
2565.0
23899
876.44
1765.7
3253.0
9876.9
我一直在使用的代碼:
df['col2'] = df['col2'].str.replace(r"[a-zA-Z]",'')
df['col2']=df['col2'].fillna('').str.replace(',',"").astype(float)
請建議如何解決這個問題。
使用Series.replace
和匹配“不是數字和點”的正則表達式
df['col2'] = df.col2.replace('[^\d.]', '', regex=True).astype(float)
Output
col2
0 2565.00
1 23899.00
2 876.44
3 1765.70
4 3253.00
5 9876.90
df['col2'] = df['col2'].str.replace(r'[a-zA-Z,]','', regex=True).astype(float)
print (df)
col2
0 2565.00
1 23899.00
2 876.44
3 1765.70
4 3253.00
5 9876.90
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.