Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Add one column's value to another if index exists

Tags:

python

pandas

I have two dataframes:

A:

   foo   bar   foo2  
0   1     1     1      
1   2     2     2
2   3     3     3
3   3     3     3

B:

   foo
0   1
2   2
3   1 
4   5

I would like to add up values of B whose index exists in A to a column of A (on the row with corresponding index) WITHOUT values from B which have no corresponding index in A being added or removing indices not present in both A and B:

   foo   bar   foo2  
0   2     1     1      
1   2     2     2
2   5     3     3
3   6     3     3

I feel like this should be straight forward but using add and concat I end up with either not all rows from A or a union of A and B

like image 359
hugydafa Avatar asked Dec 20 '25 15:12

hugydafa


1 Answers

Simple, straightforward, and efficient - use set operations to get the intersection of the indices, then perform loc based arithmetic -

i = A.index.intersection(B.index)
j = A.columns.intersection(B.columns)

A.loc[i, j] += B.loc[i, j]

A
   foo  bar  foo2
0    2    1     1
1    2    2     2
2    5    3     3
3    4    3     3
like image 53
cs95 Avatar answered Dec 22 '25 04:12

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!