0

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.

1
  • 1
    Have you tried to rearange the columns after you have joined them? Also, what is the output when you join them? Commented May 28, 2020 at 18:41

3 Answers 3

1

IIUC:

new_df = df.merge(df1, on='Role').drop('country', axis=1)
new_df = new_df[['first', 'last', 'Role', 'Rating']]
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way I can do it without explicitly giving the column names?
0

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

2 Comments

Thanks Balaji ! It works.. But is there any way to get it without explicitly mentioning column names?. If I can get by slicing or something, that would be great.. Its hard to mention all the column names for large datasets..
Can't you get the final list of columns from the column names of the dataframe using df.columns.tolist() ?
0

@Moahmed you can try the below approach:

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

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

df2.head()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.