Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])
df

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading