如何用正则表达式替换数据帧中的列值?

2024-04-28 13:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用'ASUS'或'ACER'(大写)替换下列中的值,即只要值中有单词(忽略大小写)'ACER',只需将其替换为'ACER',将单词'ASUS*'替换为'ASUS'。我使用下面的Pandas文档中的示例屏幕截图作为示例。我应用了正则表达式函数,但它似乎不起作用——输出时什么也没发生。我的代码:

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笔记本中的输出:

数组(['asus','asus ZEN','Acer','Acer Swift',dtype=object)

所使用的示例:

Pandas Example

Pandas Link Here

非常感谢您的帮助和一点解释

可接受的解决方案:

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()

输出:

数组(['ASUS','ACER'],dtype=object)


Tags: true示例单词replaceregexswiftstrzen
2条回答
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)

相关问题 更多 >