nbecker
nbecker

Reputation: 1729

merging 2 dataframes in pandas using 1 to supply missing values for the other

I am trying to merge 2 dataframes. They look like this:

df1 =
          e   u
0  0.095473   1
1  0.275177   3
2  0.239138   5
3  0.123721   7
4  0.033521   9
5  0.007609  11
6  0.001542  13

df2 =
          e   u
0  0.239847   5
1  0.145069   7
2  0.047716   9
3  0.011630  11
4  0.002493  13

I want a dataframe that has the values from df2, but using df1 to supply the missing values. The 'index' is 'u'. As you see, df2 has the same 'u' values as df1, but some are missing (df1 has 1,3,5,7,9,11,13 which df2 has 5,7,9,11,13).

Upvotes: 0

Views: 57

Answers (1)

ZJS
ZJS

Reputation: 4051

First set your indexes to u then update df1 with df2

df1 = df1.set_index('u')
df2 = df2.set_index('u')

df1.update(df2)#does update in place does not return a copy
print df1

output of df1 is now....

           e
u
1   0.095473
3   0.275177
5   0.239847
7   0.145069
9   0.047716
11  0.011630
13  0.002493

Upvotes: 1

Related Questions