From a loop I have a variable A:
aa = pd.Series(np.random.randn(5))
aaaa = []
aaaa.append(aa.loc[[1]])
aaaa.append(aa.loc[[4]])
aaaa
[1 0.07856
dtype: float64, 4 0.94552
dtype: float64]
Now I would like to sum up (or do any other calculation) the elements within A. I tried with the sum-function, but unfortunately it does not work. For instance,
B = sum(aaaa)
gives me
1 NaN
4 NaN
dtype: float64
I have found below question and solutions, however, it does not work for my problem as the TO has only one list, and not several lists appended to each other (with different indexing)
edit4: As I have to run this multiple times, I timed both answers:
%timeit sum([i.values for i in aaaa])
3.78 µs ± 5.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit pd.concat(aaaa).sum()
560 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
surprisingly the "loop" inside the sum is much faster than the pd.Series.concat().sum() function
edit5: to add in case someone else has the same problem: in case if it's not know whether the input is a pd.Series or a list of pd.Series, one could do following:
res = sum(aa) if isinstance(aa, pd.Series) else sum([i.values for i in aa])