Pandas: compare two columns and find cells that are both not empty

Viewed 483

I have a df with 5 columns but I am interested only in columns A, B and C.

A and B contain multiple names, C is an empty column.
I want to fill C column with the value of B if and only if A and B are both not empty (!="").

The desired output would be something like this :

example output

Any help would be appreciated. Thank you in advance.

2 Answers

To solve this issue I used NumPy's np.where :

import numpy as np

df['C'] = np.where((df['A'] != '') & (df['B'] != ''), df['B'], '')

This should be possible with a single liner

df.C = df.B if df.A.any() else ''

You can modify df.A.any() to any condition you want such as not df.A.empty()

but this solves your issue.

Related