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

Pandas replace specific cells with corresponding values from another series

Let’s say I have the following pd.DataFrame:

INDEX a b c
A 5 7 2
B 3 2 1
C 9 6 3

And also the following pd.Series:

a b c
-1 -4 -5

I would like to replace the values is the DataFrame that are bigger then, or equal to 6, with the respective values from the Series, according to the column name.
For example, I would like to replace cell Ab (7>6), with -4 (since cell Ab is in col b, and the series had -4 in that index).
In the above example, the DataFrame will look like:

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

~ a b c
A 5 -4 2
B 3 2 1
C -1 -4 3

I know how to identify the required cells using:
df[df>=6], but when I’m trying to assign the series (df[df>=6]=series) I get an error.

Thanks 🙂

>Solution :

You can mask and fillna:

out = df.mask(df.ge(6)).fillna(s, downcast='infer')

output:

       a  b  c
INDEX         
A      5 -4  2
B      3  2  1
C     -1 -4  3
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