1

I have a dataframe called 'qtm' that looks like the following:

Name Strength Weakness
Voltron NaN Flower
Joe punch candy
Voltron Speed Time

I want the Python equivalent of the SQL code below:

UPDATE qtm
SET Strength = 'Fire' 
WHERE Name = 'Voltron' AND Strength = 'NaN'

So I could get the following dataframe back:

Name Strength Weakness
Voltron Fire Flower
Joe punch candy
Voltron Speed Time

I tried the following but it didn't work:

qtm.loc[qtm['Name'] == 'Voltron' & qtm['Strength'] == 'NaN', 'Strength']='Fire'

I tried the following solutions but ultimately couldn't get it to work:

[https://stackoverflow.com/questions/19226488/change-one-value-based-on-another-value-in-pandas]

&

[https://stackoverflow.com/questions/64980121/change-value-of-a-column-based-on-another-column?noredirect=1&lq=1]

1 Answers1

1

Add parentheses with test missing values by Series.isna:

qtm.loc[(qtm['Name'] == 'Voltron') & (qtm['Strength'].isna()), 'Strength']='Fire'

Or use Series.fillna for set NaNs by mask:

#one condition () not necessary
m = qtm['Name'] == 'Voltron'
qtm.loc[m, 'Strength'] = qtm.loc[m, 'Strength'].fillna('Fire')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • this worked. would equating df == ‘not avail’ also work if for instance the Strength value I were looking for was ‘not avail’ instead of NaN? – That Guy XY Apr 08 '21 at 11:32
  • @ThatGuyXY - yes, then use `(qtm['Strength']== 'not avail')` – jezrael Apr 08 '21 at 11:32