Frank AK
Frank AK

Reputation: 1781

How to update a DataFrame with a another DataFrame by its index?

I have a origin data frame as below:

0          0
1       6.19
2       6.19
3      16.19
4      16.19
5     179.33
6     179.33
7     179.33
8     179.33
9     179.33
10    179.33
11         0
12    179.33
13    179.33
14         0
15         0
16         0
17         0
18         0
19     11.49
20     11.49
21      7.15
22      7.15
23     16.19
24     16.19
25     17.85
26     17.85

And the second Data Frame is:

2       3.19
4      16.19
6     179.33
8     179.33
10    179.33
13    179.33
20     11.49
22      7.15
24     16.19
26     17.85

You can see the first column is index, and I want it to be updated according the second data list.

For example:

0          0
1       6.19
2       6.19

Since my second data Frame is 3.19 with index at 2. so my expect output should be like:

0          0
1       6.19
2       3.19

How to I reach that? BTW, I have try to do that like:

for i in df.index:
    new = df2.aa[i]
    if new:
        df.loc['aa'][i]=new

But it should have a good way to do that in pandas, plz help me.

Upvotes: 0

Views: 37

Answers (1)

jezrael
jezrael

Reputation: 862581

Use Series.combine_first or Series.update:

df1['col'] = df2['col'].combine_first(df1['col'])

Or:

df1['col'].update(df2['col'])

print (df1)
       col
0     0.00
1     6.19
2     3.19
3    16.19
4    16.19
5   179.33
6   179.33
7   179.33
8   179.33
9   179.33
10  179.33
11    0.00
12  179.33
13  179.33
14    0.00
15    0.00
16    0.00
17    0.00
18    0.00
19   11.49
20   11.49
21    7.15
22    7.15
23   16.19
24   16.19
25   17.85
26   17.85

Upvotes: 4

Related Questions