Python Dataframe: If Value in Column Equals String AND Value in Second Column is Null, Replace the Null Cell With Another String

Advertisements

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:

  • 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:

>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

Leave a ReplyCancel reply