I have 2 dataFrames
df1
B C
A
0 300 6
1 400 7
2 500 8
3 600 9
df2
B C
A
2 433 99
3 555 99
This is how I construct them:
df1 = pd.DataFrame({'A': [0, 1, 2, 3],
'B': [300, 400, 500, 600],
'C': [6, 7, 8, 9]})
df1.set_index('A', inplace=True)
df2 = pd.DataFrame({'A': [2, 3],
'B': [433, 555],
'C': [99, 99]})
df2.set_index('A', inplace=True)
I want to replace all rows from df1
with the rows from df2
based on the index, the result should look like this:
df_result
B C
A
0 300 6
1 400 7
2 433 99
3 555 99
What is the most elegant way to do this?
This is what update
is meant for:
df1.update(df2)
>>> df1
B C
A
0 300.0 6.0
1 400.0 7.0
2 433.0 99.0
3 555.0 99.0
Try combine_first
:
df2.combine_first(df1)
Output:
B C
A
0 300.0 6.0
1 400.0 7.0
2 433.0 99.0
3 555.0 99.0
Notice using .loc
will not change the type of column
df1.loc[df2.index,:]=df2
df1
Out[20]:
B C
A
0 300 6
1 400 7
2 433 99
3 555 99
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With