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 Dataframe: If Value in Column Equals String AND Value in Second Column is Null, Replace the Null Cell With Another String

I have the following sample python dataframe below:

Type Value
A sesame
B
A
C tea
A bun

The code to create the table is below:

import pandas as pd
df = pd.DataFrame({'Type':["A","B","A", "C", "A"],'Value':["sesame", None, None, "tea", "bun"]})

I want to do the following:

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

  • If Type column equals "A" AND Value column is null, then replace the null with "custard"
  • If Type column equals "B" AND Value column is null, then replace null with "peanuts"
  • Otherwise leave Value column as is

My desired output table is below:

Type Value
A sesame
B peanuts
A custard
C tea
A bun

I can’t even seem to figure out the first bullet point. I tried the following code:

df.loc[df['Type'] == 'A', ['Value']].fillna(value='custard', axis=1)

But it produces the wrong output:
enter image description here

>Solution :

Use the fact the empt values comparison returns false in equality.
Parse the resultant index to change the values to your desire.
If needed do the aproach in steps.
if the query is not empty, try to change de value.

I implemented the simplier and direct aproach.

import pandas as pd
df = pd.DataFrame({'Type':["A","B","A", "C", "A"],'Value':["sesame", None, None, "tea", "bun"]})
df.loc[df.query("Value!=Value and Type == 'A'").index,'Value'] = 'custard'
df.loc[df.query("Value!=Value and Type == 'B'").index,'Value'] = 'peanuts'
df
    Type    Value
--  ------  -------
 0  A       sesame
 1  B       peanuts
 2  A       custard
 3  C       tea
 4  A       bun
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