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

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Apr 11 15:37:21 EDT 2018


On Apr 11, 2018 20:52, zljubisic at gmail.com wrote:
>
> I have a dataframe:
>
> import pandas as pd
> import numpy as np
>
> df = pd.DataFrame( { 'A' : ['a', 'b', '', None, np.nan],
>                      'B'  : [None, np.nan, 'a', 'b', '']})
>
>       A     B
> 0     a  None
> 1     b   NaN
> 2           a
> 3  None     b
> 4   NaN
>
>
> I would like to create column C in the following way:
> column C = column B if column B is not in [None, '', np.nan]
> else column A
>
> How to do that?
>
> I tried:
>
> df['C'] = df[['A', 'B']].apply(lambda x: x[1] if x[1] in [None, '', np.nan] else x[0])
>
> but I got all np.nan's.

This is another approach:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html


More information about the Python-list mailing list