簡體   English   中英

如何用正則表達式替換 pandas dataframe 中的列值?

[英]How to replace column values in a pandas dataframe with regex?

我想用'ASUS'或'ACER'(大寫)替換下面列中的值,即只要值中有單詞(忽略大小寫)'acer',只需將其替換為'ACER' , 和單詞 'asus *' 替換為 'ASUS'。 我使用下面來自 Pandas 文檔的示例屏幕截圖作為示例。 我應用了正則表達式 function,但它似乎不起作用 - output 沒有任何反應。 我的代碼:

dfx = pd.DataFrame({'Brands':['asus', 'ASUS ZEN', 'Acer','ACER Swift']})
dfx = dfx.replace([{'Brands': r'^asus.$'}, {'Brands': 'ASUS'}, {'Brands': r'^acer.$'}, {'Brands': 'ACER'}], regex=True)
dfx['Brands'].unique()

Jupyter筆記本中的Output:

數組(['華碩','華碩 ZEN','宏碁','ACER Swift'],dtype=object)

使用的 Pandas 文檔示例:

熊貓示例

Pandas 鏈接在這里

非常感謝任何有一點解釋的幫助。

接受的解決方案:

dfx = pd.DataFrame({'Brands':['asus', 'ASUS ZEN', 'Acer','ACER Swift']})

dfx['Brands'] =  dfx['Brands'].str.lower().str.replace('.*asus.*', 'ASUS', regex=True).str.replace('.*acer.*', 'ACER', regex=True)
OR
dfx['Brands'] = dfx.Brands.apply(lambda x: re.sub(r".*(asus|acer).*", lambda m: m.group(1).upper(), x, flags=re.IGNORECASE))

dfx['Brands'].unique()

Output:

數組(['華碩','ACER'],dtype =對象)

dfx.Brands.apply(lambda x: re.sub(r".*(asus|acer).*", lambda m: m.group(1).upper(), x, flags=re.IGNORECASE))

請試試

dfx['Brands'] =  dfx['Brands'].str.lower().str.replace('.*asus.*', 'ASUS', regex=True).str.replace('.*acer.*', 'ACER', regex=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM