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
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
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