WillacyMe
WillacyMe

Reputation: 582

How do you concatenate two differently named columns together in pandas?

I'd like to create a new dataframe where A and B or kept but column B is renamed and column A and C get repeated underneath it but C's value's being placed into the renamed column C (D).

df =  A      B   C
    'bob'    1   4
    'john'   2   5
    'mick'   3   6

This is what the new dataframe should look like.

new_df = A      D
       'bob'    1  
       'john'   2  
       'mick'   3  
       'bob'    4  
       'john'   5  
       'mick'   6  

Upvotes: 3

Views: 91

Answers (1)

Nickil Maveli
Nickil Maveli

Reputation: 29711

Alternative-1:

Use lreshape to convert from wide to long formatted DF:

pd.lreshape(df, {'D': ['B', 'C']})

Image


Alternative-2:

If you want to perform concatenation, then do:

df = df.set_index(['A'])
pd.concat([df['B'], df['C']]).reset_index(name='D')

Image

Upvotes: 8

Related Questions