2

Here is the original post: Python Pandas update a dataframe value from another dataframe

df1 and df2 have the same data structure.

The original column order: assignee id issuetype key

The problem is that after runing the following code:

df1.set_index('key',inplace=True)
df1.update(df2.set_index('key'))
df1.reset_index() 

The column order of df1 changed to this:

key assignee id issuetype

How can I recover the initial structure after update one dataframe with another dataframe? thanks.

1 Answer 1

2

Change order by original columns by DataFrame.reindex:

cols = df1.columns
df1.set_index('key',inplace=True)
df1.update(df2.set_index('key'))
df1 = df1.reset_index().reindex(cols, axis=1)
print (df1)
Sign up to request clarification or add additional context in comments.

13 Comments

I tired it, it didn't work. The "Key" is still the first column.
@Ming - Sorry, answer was edited. cols is necessary use for variable
it didn't work on my side, here is my code: df1=pd.read_csv("update_1.csv") df2=pd.read_csv("update_2.csv") cols = df1.columns df1.set_index('key',inplace=True) df1.update(df2.set_index('key')) df1.reset_index().reindex(cols, axis=1)
@Ming - Is assigned back output? Like df1 = df1.reset_index().reindex(cols, axis=1) and then print (df1) ? Answer was edited.
Yes, the printed out structure is not recovered.
|

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.