我想創(chuàng)建一個函數(shù)來從熊貓數(shù)據(jù)框中刪除特殊字符,但也傳遞一個參數(shù)來保留所需的字符。def strip_characters(c, req_char = ''): spec_chars = ["!",'"',"#","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_","`","{","|","}","~","–"] new_spec = spec_chars.remove(req_char) for char in spec_chars: c = c.str.replace(char, ' ') return cdf['col'] = df['col'].apply(strip_characters,',') # passing a comma to retain the character# df['col'] = ['Dining Room', 'Pre-War', 'Laundry in Building', '&Lobby']
1 回答

慕桂英546537
TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
嘗試這個,
import pandas as pd
df = pd.DataFrame({'col':['Dining Room', 'Pre-War', 'Laundry in Building', '&Lobby']})
# ([^) means match anything but word character
# "[^\w+|,]" to exclude specific character's from being replaced
df['col'].str.replace("[^\w+]"," ")
輸出
0 Dining Room
1 Pre War
2 Laundry in Building
3 Lobby
添加回答
舉報
0/150
提交
取消