Skip to content
Advertisement

How to replace values in pandas data frame by dictionary?

I have a problem with pandas and replacing values. I have a table with animals and their alleles looks that:

JavaScript

And I need to change values of Top1 and Top2 by a specific Key for each row.

For example: if values in same rows will be = C & A, I will replace it to A & B, if row == TT will be BB etc. (key is in if/else below).

I got an answer in another post how to do it by dictionary but I can’t handle with that double condition (if it will be one condition for ex. if A in first row, replace to B, it will be ok). So I just put it into if/else loop and it works… I mean worked, it worked until files were large. Now it soo slow. 300mb file can be processing 30 min on a standard desktop.

That’s how my code look now:

JavaScript

X – counting errors. And I know, that code is ugly, so I tried to put the dictionary method. My attempt:

JavaScript

But I got a bad output. The only A1_top is changed, and usually it a bad symbol. Can someone help me translate my ugly code to the dictionary and explain it? And do I think properly that will be a faster solution?

For sure, expecting output (there are no headers in output, below for clarity)

JavaScript

Advertisement

Answer

A simple trick, not to say the best, but it works: [Create a dummy column to do mapping or df[col].apply ]

JavaScript

Create dictionary, mapping all your requirements: I give 1 here

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement