Pandas, create new column if previous column(s) are not in [None, '', np.nan]

José María Mateos chema at rinzewind.org
Wed Apr 11 15:19:22 EDT 2018


On Wed, Apr 11, 2018, at 14:48, zljubisic at gmail.com wrote:
> I have a dataframe:
> [...]

This seems to work:

df1 = pd.DataFrame( { 'A' : ['a', 'b', '', None, np.nan],
                                                  'B'  : [None, np.nan, 'a', 'b', '']})
df1['C'] = df1[['A', 'B']].apply(lambda x: x[0] if x[1] in [None, '', np.nan] else x[1], axis = 1)

Two notes:

- Do apply() on axis = 1, so you process every row.
- You lambda function wasn't entirely correct, if I understood what you wanted to do.

Cheers,

-- 
José María (Chema) Mateos
https://rinzewind.org/blog-es || https://rinzewind.org/blog-en


More information about the Python-list mailing list