简体   繁体   English

如何用正则表达式替换 pandas dataframe 中的列值?

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

I want to replace the the values in the column below with either 'ASUS' or 'ACER' (in caps) ie as long as there is the word (ignore case) 'acer' in the value, just replace it to 'ACER', and the word 'asus *' replace with 'ASUS'.我想用'ASUS'或'ACER'(大写)替换下面列中的值,即只要值中有单词(忽略大小写)'acer',只需将其替换为'ACER' , 和单词 'asus *' 替换为 'ASUS'。 I used below example screenshot from Pandas documentation as an example.我使用下面来自 Pandas 文档的示例屏幕截图作为示例。 I applied regex function and it doesn't seem to work - nothing happens at the output.我应用了正则表达式 function,但它似乎不起作用 - output 没有任何反应。 My code:我的代码:

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

Output in Jupyter notebook: Jupyter笔记本中的Output:

array(['asus', 'ASUS ZEN', 'Acer', 'ACER Swift'], dtype=object)数组(['华硕','华硕 ZEN','宏碁','ACER Swift'],dtype=object)

Pandas documentation example used:使用的 Pandas 文档示例:

熊猫示例

Pandas Link Here Pandas 链接在这里

Any help with a little explanation is very much appreciated.非常感谢任何有一点解释的帮助。

ACCEPTED SOLUTION(S):接受的解决方案:

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: Output:

array(['ASUS', 'ACER'], dtype=object)数组(['华硕','ACER'],dtype =对象)

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

Please try请试试

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