Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Rows in Pandas DataFrame with Other DataFrame Based on Index

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?

like image 803
Egirus Ornila Avatar asked Dec 11 '18 15:12

Egirus Ornila


3 Answers

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
like image 109
sacuL Avatar answered Oct 04 '22 02:10

sacuL


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
like image 36
Scott Boston Avatar answered Oct 04 '22 03:10

Scott Boston


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
like image 32
BENY Avatar answered Oct 04 '22 04:10

BENY