Mohamed Muhsin
Mohamed Muhsin

Reputation: 1

Replacing columns with different Dataframe

I have two dataframes,namely 'df' and 'df1'

df
Out[14]: 
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]: 
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow

Expected output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

Upvotes: 0

Views: 35

Answers (3)

user3226869
user3226869

Reputation: 11

@Moahmed you can try the below approach:

df2 = pd.concat([df,df1], axis = 1)

df2 = df2[['first','last','Role','Rating']]

df2.head()

Upvotes: 0

Balaji Ambresh
Balaji Ambresh

Reputation: 5037

Could you give this a shot?

df1.join(df2, lsuffix='', rsuffix='r_')[["first", "last", "Role", "Rating"]]

Output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100

Upvotes: 0

Bruno Mello
Bruno Mello

Reputation: 4618

IIUC:

new_df = df.merge(df1, on='Role').drop('country', axis=1)
new_df = new_df[['first', 'last', 'Role', 'Rating']]

Upvotes: 1

Related Questions