1

I am having a list 'final_value' which contains panda series with data below. I need to add the vales of multiple panda series into one series. Can anyone please help me.

Need to add values according to their index value.

I tried final_value[i].add(final_value[i+1]) in a loop. But did not work

Data:

[0      0.000000
1     14.522873
2     21.677418
3     10.791055
4      0.000000
5      7.176507
Name: (FDIUSGD Index, PX_LAST), Length: 6, dtype: float64, 
0    -16.276548
1    -16.276548
2    -15.761264
3    -16.276548
4    -16.276548
5    -17.822402
Name: (USHBMIDX Index, PX_LAST), Length: 6, dtype: float64, 
0      0.000000
1      5.972322
2     15.255200
3     -3.498313
4      2.698414
5      3.083199
Name: (USPHNSA Index, PX_LAST), Length: 6, dtype: float64, 

Expected output:

0     -16.276548
1     4.218647
2     21.171354
3    -8.983806
4    -13.578134
5    -7.562696

Thanks!

Arvinth Kumar
  • 964
  • 3
  • 15
  • 32

3 Answers3

4
final_value = [
    pd.Series(1, range(5)),
    pd.Series(2, range(5)),
    pd.Series(3, range(5))
]

Just use sum

sum(final_value)

0    6
1    6
2    6
3    6
4    6
dtype: int64

Or you could use np.sum

pd.Series(np.sum([s.values for s in final_value], 0), final_value[0].index)

0    6
1    6
2    6
3    6
4    6
dtype: int64
piRSquared
  • 285,575
  • 57
  • 475
  • 624
3

Let's try this:

from functools import reduce
reduce(pd.Series.add, final_value)

Example:

print(final_values)

Input df:

[0     0.000000
1    14.522873
2    21.677418
3    10.791055
4     0.000000
5     7.176507
Name: 1, dtype: float64, 0   -16.276548
1   -16.276548
2   -15.761264
3   -16.276548
4   -16.276548
5   -17.822402
Name: 1, dtype: float64, 0     0.000000
1     5.972322
2    15.255200
3    -3.498313
4     2.698414
5     3.083199
Name: 1, dtype: float64]


from functools import reduce
reduce(pd.Series.add,final_value)

Output:

0   -16.276548
1     4.218647
2    21.171354
3    -8.983806
4   -13.578134
5    -7.562696
Name: 1, dtype: float64

Timings....

John's Method

%timeit pd.concat(final_value, axis=1).sum(axis=1)

100 loops, best of 3: 3.06 ms per loop

functools reduce method

%timeit reduce(pd.Series.add, final_value)

1000 loops, best of 3: 551 µs per loop

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
2

Use pd.concat on axis=1 and sum row-wise

In [597]: pd.concat(final_value, axis=1).sum(axis=1)
Out[597]:
0   -16.276548
1     4.218647
2    21.171354
3    -8.983806
4   -13.578134
5    -7.562703
dtype: float64

Details

In [598]: final_value
Out[598]:
[0     0.000000
 1    14.522873
 2    21.677418
 3    10.791055
 4     0.000000
 5     7.176500
 Name: 1, dtype: float64, 0   -16.276548
 1   -16.276548
 2   -15.761264
 3   -16.276548
 4   -16.276548
 5   -17.822402
 Name: 1, dtype: float64, 0     0.000000
 1     5.972322
 2    15.255200
 3    -3.498313
 4     2.698414
 5     3.083199
 Name: 1, dtype: float64]
Zero
  • 74,117
  • 18
  • 147
  • 154