Stefano Fedele - 1 year ago 96

Python Question

I have two pandas dataframes, say df1 and df2, of some size each but with different indexes and I would like to sum up the two dataframes element by element. I provide you an easy example to better understand the problem:

`dic1 = {'a': [3, 1, 5, 2], 'b': [3, 1, 6, 3], 'c': [6, 7, 3, 0]}`

dic2 = {'c': [7, 3, 5, 9], 'd': [9, 0, 2, 5], 'e': [4, 8, 3, 7]}

df1 = pd.DataFrame(dic1)

df2 = pd.DataFrame(dic2, index = [4, 5, 6, 7])

so df1 will be

`a b c`

0 3 3 6

1 1 1 7

2 5 6 3

3 2 3 0

and df2 will be

`c d e`

4 7 9 4

5 3 0 8

6 5 2 3

7 9 5 7

now if type

`df1 + df2`

what I get is

`a b c d e`

0 NaN NaN NaN NaN NaN

1 NaN NaN NaN NaN NaN

2 NaN NaN NaN NaN NaN

3 NaN NaN NaN NaN NaN

4 NaN NaN NaN NaN NaN

5 NaN NaN NaN NaN NaN

6 NaN NaN NaN NaN NaN

7 NaN NaN NaN NaN NaN

How can I make pandas understand that I want to sum up the two dataframe just element by element?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

**UPDATE:** much better solution from piRSquared:

```
In [39]: df1 + df2.values
Out[39]:
a b c
0 10 12 10
1 4 1 15
2 10 8 6
3 11 8 7
```

**Old answer:**

```
In [37]: df1.values + df2.values
Out[37]:
array([[10, 12, 10],
[ 4, 1, 15],
[10, 8, 6],
[11, 8, 7]], dtype=int64)
In [38]: pd.DataFrame(df1.values + df2.values, columns=df1.columns)
Out[38]:
a b c
0 10 12 10
1 4 1 15
2 10 8 6
3 11 8 7
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**