[英]Is there way to remove only BAD characters from a string in Python/pandas?
[英]Is there a way in python/pandas to remove a particular set of characters from a string
有沒有辦法一次性從python字符串中刪除一組特定的字符?
str='23.889,45 €'
我想刪除點 '.' 和 '€' 符號,但我不想像str.replace('€','').replace('.',''), whereby replacing the characters with white space
那樣使用replace()
函數兩次str.replace('€','').replace('.',''), whereby replacing the characters with white space
。
在 SAS 中有一個函數compress
,它需要一個要刪除的字符列表,在應用該函數時,將刪除 SAS 字符串中存在的所有字符。 例如: compress(str,'.€')
將返回str as 23889,45
。
Python中是否也有相應的函數?
多字符去除
您可以使用正則表達式來執行多個字符替換。
字符類是[...]
有字符、字符范圍或速記字符類,交替組是(...|....|.....)
像模式。 在這兩種構造中使用文字字符可能會出現問題,但re.escape
來拯救:它將確保您傳遞給正則表達式的字符被視為文字字符。
查看 Python 3 演示:
>>> import re
>>> charsToRemove = ["$", ".", "€"]
>>> s='23.889,45 €'
>>> print(re.sub("|".join([re.escape(x) for x in charsToRemove]), "", s)) # Alternation group
23889,45
>>> print(re.sub(r"[{}]+".format("".join([re.escape(x) for x in charsToRemove])), "", s)) # Character class
23889,45
在 Pandas 中,你會使用
df['col'].str.replace(r"[{}]+".format("".join([re.escape(x) for x in charsToRemove])),"", regex=True, inplace=True)
請注意,字符類方法 ( [...]+
) 會運行得更快。
多次更換
您可以考慮創建一個替換字典,然后將其與 Pandas replace
一起使用:
>>> from pandas import DataFrame
>>> import pandas as pd
>>> import regex
>>> repl_list = {'€':'$', ',':'.', r'\.': ''}
>>> col_list = ['23.889,45 €']
>>> frame = pd.DataFrame(col_list, columns=['col'])
>>> frame['col'].replace(repl_list, regex=True, inplace=True)
>>> frame['col']
0 23889.45 $
要使其工作,您必須使用regex=True
參數並添加import re
因為repl_list
中的所有鍵都是正則表達式。 不要忘記在那里轉義特殊的正則表達式字符。 請參閱在正則表達式中必須轉義哪些特殊字符? 或者,您可以寫r'\\.'
作為re.escape('.')
。
您正在談論的 compress 函數必須執行以下操作:
str='23.889,45 €'
charsToRemove = ["$", ".", "€"]
def compress(str, charsToRemove):
for i in range(len(charsToRemove)):
str = str.replace(charsToRemove[i], '')
return str
print compress(str, charsToRemove) # returns '23889,45 '
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.