Alicia
Alicia

Reputation: 151

Error using conditional values in pandas dataframe

I am trying to use the following code to set a new column, wdf['Thunder'] to the value of wdf['RngT] if the word Thunderstorm is in the column wdf['Notes']. However, I keep getting the error TypeError: argument of type 'float' is not iterable. None of the columns are floats. RngT is an int, Notes is an object. Full code is:

wdf['Thunder'] = [wdf['RngT'] if 'Thunderstorm' in x else 0 for x in wdf['Notes']]

New to pandas, so would appreciate any insight.

Thanks!

Upvotes: 2

Views: 50

Answers (1)

cs95
cs95

Reputation: 402263

You may consider a performant alternative, np.where:

wdf['Thunder'] = np.where(
    wdf['Notes'].astype(str).str.contains('Thunderstorm'), wdf['RngT'], 0
)

Note that your first approach probably didn't work because your column was mixing strings and floats. Using astype(str) before checking for containment should fix that.

Upvotes: 1

Related Questions