Pandas DataFrame add column with text from two other columns depending on condition

How do I add a column with header MergeName to a Pandas DataFrame that has the text from column ShortName, but if ShortName is "None", then the MergeName value should equal the Plaintiffs column value?

This is the Pandas DataFrame data:

      Plaintiffs Gender ShortName
0           None   None      None
1           None   None      None
2    Donald Duck      M      None
3   Minnie Mouse      F    Minnie
4           None   None      None
5       John Doe      M       Doe
6           None   None      None
7           None   None      None
8           None   None      None
9           None   None      None
10          None   None      None


I’ve tried so many different things and nothing seems to work. Usually the result is only all the data from the else condition is added to the MergeName column including "None" values. Code I’ve tried include:

PlaintiffsTbl['MergeName'] = np.where(PlaintiffsTbl['ShortName'] is None, PlaintiffsTbl['Plaintiffs'],  PlaintiffsTbl['ShortName'])
PlaintiffsTbl['MergeName'] = PlaintiffsTbl['ShortName']
PlaintiffsTbl.loc[PlaintiffsTbl['MergeName'] == None, 'MergeName'] = PlaintiffsTbl['Plaintiffs']
PlaintiffsTbl['MergeName'] = [PlaintiffsTbl['Plaintiffs'] if PlaintiffsTbl['ShortName'] is None else PlaintiffsTbl['ShortName']]

Thank you Amir Hossein Shahdaei!
This code does what I was looking for:

PlaintiffsTbl['MergeName'] = PlaintiffsTbl['ShortName']
PlaintiffsTbl['MergeName'] = PlaintiffsTbl['MergeName'].fillna(PlaintiffsTbl['Plaintiffs'])

>Solution :

You can use .fillna function and after making MergeName from ShortName col fill null values of it with MergeName col

df = pd.DataFrame(
    data = [
        ['a', None],
        ['b', 1],
        [None, 2],
        [None, None],], 
    columns = ['Plaintiffs', 'ShortName']
df['MergeName'] = df['ShortName']
df['MergeName'] = df['MergeName'].fillna(df['Plaintiffs'])

    Plaintiffs  ShortName   MergeName
0   a           NaN         a
1   b           1.0         1.0
2   None        2.0         2.0
3   None        NaN         None

Leave a Reply