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

Replace Values of Multiple Columns in Pandas Dataframe More Efficiently

I have a DataFrame, df, where I would like to replace several values

user1 user2 user3
apple yoo apple
mango ram mango

Instead of doing


df['user1'] = df['user1'].replace(['apple','mango'], [0, 1])
df['user3'] = df['user1'].replace(['apple','mango'], [0, 1])
df['user2'] = df['user2'].replace(['yoo','ram'], [2, 3])


to get the final DataFrame of

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

user1 user2 user3
0 2 0
1 3 1

Is there any way I make the code above more efficient such that I can change the values of apple, mango, yoo and ram with one line of code?

>Solution :

If need set range by unique values per columns use:

cols = ['user1','user2','user3']
s = df[cols].unstack()
df[cols] = pd.Series(pd.factorize(s)[0], index=s.index).unstack(0)
print (df)
   user1  user2  user3
0      0      2      0
1      1      3      1
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