Michael Mathews Jr.
Michael Mathews Jr.

Reputation: 329

Apply a lambda function to iterate over two columns

I have a pandas df:

pd.DataFrame({'61 - 90': [np.NaN, 14, np.NaN, 9, 34, np.NaN],
         '91 and over': [np.NaN, 10, np.NaN, 1, np.NaN, 9]})

I am trying to apply a lambda function that returns False if BOTH columns for a record == np.NaN. My attempt at solving this:

df['not_na'] = df[['61 - 90', '91 and over']].apply(lambda x: False if pd.isna(x) else True)

The error message I receive:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 61 - 90')

Upvotes: 1

Views: 1518

Answers (2)

nishant thakkar
nishant thakkar

Reputation: 96

To do this using a lambda function over a data frame For elementwise operations. we need to use applymap

df[['61 - 90', '91 and over']].applymap(lambda x: False if pd.isna(x) else True)

the documentation for applymap fuction is availablein the link below https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

Why don't you do:

df['not_na'] = df[['61 - 90', '91 and over']].notnull().any(axis=1)

Upvotes: 2

Related Questions