Pandas using apply function to create a column based on value of another column

27 views Asked by At

I'm trying to create column C that is equal to column A if column B is not nan, else make column C equal to column B.

I've tried this apply function:

df = pd.DataFrame({'a': [1, 1, 1, 1, 1], 'b': [np.nan, np.nan, 2, 2, 2]})
df['c'] = df.apply(lambda row: row['a'] if np.isnan(row['b']) else row['b'])

But get this error: KeyError: 'b'

I still don't understand why I get this error if the dataframe clearly does have a 'b' column. Am I using the apply function the wrong way?

0

There are 0 answers