[英]remove special characters and string from df columns in python
當前,我的列是對象類型,並且我正在嘗試將其轉換為數字類型。 但是由於其中包含特殊字符和字符串,因此顯示了錯誤。
錯誤:
ValueError: Unable to parse string "7`" at position 3298
碼:
data['col1']=pd.to_numeric(data.col1)
因此,我想從僅需要數字和col1作為其中之一的列中刪除特殊的char和string。 有什么建議的解決方案嗎?
將str.replace
與正則表達式模式一起使用。
例如:
df = pd.DataFrame({"col1": ["7`", "123", "AS123", "*&%3R4"]})
print(pd.to_numeric(df['col1'].str.replace(r"[^\d]", "")))
輸出:
0 7
1 123
2 123
3 34
Name: col1, dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.