简体   繁体   中英

merging columns in one sing dataframe in python

Here is a fake dataframe:

import pandas as pd

employee = {'EmployeeID' : [0, 1, 2, 3, 4, 5, 6],
         'LastName' : ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
         'Name' : ['w', 'x', 'y', 'z', None, None, None],
         'Name2' : ['H','I', None, 'J', 'K', 'L', 'M']}

df = pd.DataFrame(employee)

Now, I want to do 2 simple things which I could not successfully done after reading many documents.

1) I want to merge Name and Name2 as 'Name' column. If I want it

'Name' : ['w', 'x', 'y', 'z', 'K', 'L', 'M']

should I try something like left inner join ?? I am very confusing with this.

2) another merge should be done with LastName and Name. I just want them to be together like.

'Name' : ['aw', 'bx', 'cy', 'dz', 'e', 'f', 'g']

I feel like this should be really simple, but I am still learning. If someone can help me on this, I would be very appreciate!

Thanks

This should work:

import pandas as pd

employee = {'EmployeeID' : [0, 1, 2, 3, 4, 5, 6],
            'LastName' : ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
            'Name' : ['w', 'x', 'y', 'z', None, None, None],
            'Name2' : ['H','I', None, 'J', 'K', 'L', 'M']}

df = pd.DataFrame(employee)

df['Name'] = df['Name'].fillna(df['Name2'])
df['FullName'] = df['LastName'] + df['Name']

df = df.drop('Name2', 1)

#    EmployeeID LastName Name FullName
# 0           0        a    w       aw
# 1           1        b    x       bx
# 2           2        c    y       cy
# 3           3        d    z       dz
# 4           4        e    K       eK
# 5           5        f    L       fL
# 6           6        g    M       gM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM