Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Pandas Replace multiple values in one column with dict

I have the below df as an example

Product Code Product Type Price
01478 ELC £119.00
01479 GRN £159.00
01514 PWR £100.00
01617 ELC £119.00
01819 ELC – GRN – PWR £300.00
01819 ELC – GRN – PWR £300.00

I am trying to change multiple values in the ‘Product Type’ column using a dict

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df['Product Type'] = df['Product Type'].str.replace('ELC', 'Electric')
df['Product Type'] = df['Product Type'].str.replace('GRN', 'Green')
df['Product Type'] = df['Product Type'].str.replace('PWR', 'Power Supply')

When I use this it changes the values and works, even for ELC – GRN – PWR

However when I try to use a dict method just to improve code readability and make it more simple instead of loads of str.replace lines.

dict = {
    'ELC' : 'Electric', 
    'GRN' : 'Green', 
    'PWR': 'Power Supply', 
    '-' : ' '}

It only changes the single ELC to Electric, and GRN to Green but does not change the ELC – GRN – PWR to Electric – Green – Power Supply.

Can I ask why this happens and what the solution is?

I’ve looked at many different approaches in stack but nothing seems to work effectively.

Thank You 🙂

>Solution :

you can use regex inside df.Series.replace (without str):

df['Product Type'] = df['Product Type'].replace(dict, regex=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading