0

I have a bit of a weird pandas question.

I have a master Dataframe:

   a   b   c
0  22  44  55
1  22  45  22
2  44  23  56
3  45  22  33

I then have a dataframe in a different dimension which has some over lapping index's and column names

index   col_name  new_value
0        a          111 
3        b          234

I'm trying to then say if you find a match on index and col_name in the master dataframe, then replace the value.

So the output would be

   a   b   c
0  111  44  55
1  22  45  22
2  44  23  56
3  45  234  33

I've found "Combine_first" but this doesn't work unless I pivot the second dataframe (which I can't do in this scenario)

1 Answer 1

5

This is update problem

df.update(updated.pivot(*updated.columns))
df
Out[479]: 
       a      b   c
0  111.0   44.0  55
1   22.0   45.0  22
2   44.0   23.0  56
3   45.0  234.0  33

Or

df.values[updated['index'].values,df.columns.get_indexer(updated.col_name)]=updated.new_value.values
df
Out[495]: 
     a    b   c
0  111   44  55
1   22   45  22
2   44   23  56
3   45  234  33
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. My fault for not labelling but in your example is df the master dataframe and updated the one to add on?
@fred.schwartz yes , it is
And yes, using @W-B's method of pivoting dim.pivot(*dim.columns).combine_first(master) works.
@coldspeed thank you so much ! Without your support, this would not have been possible!

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.