I have a 16x10 panda dataframe with 1x35000 arrays (or NaN) in each cell. I want to take the element-wise mean over rows for each column.
1 2 3 ... 10
1 1x35000 1x35000 1x35000 1x35000
2 1x35000 NaN 1x35000 1x35000
3 1x35000 NaN 1x35000 NaN
...
16 1x35000 1x35000 NaN 1x35000
To avoid misunderstandings: take the first element of each array in the first column and take the mean. Then take the second element of each array in the first column and take the mean again. In the end I want to have a 1x10 dataframe with one 1x35000 array each per column. The array should be the element-wise mean of my former arrays.
1 2 3 ... 10
1 1x35000 1x35000 1x35000 1x35000
Do you have an idea to get there elegantly preferably without for-loops?
Approach #1 : Loopy
Given the mixed dtype input data, we might want to loop through for performance efficiency. So, looping with explicit loops or under-the-hood usages of
.apply/.applymap
would be the solutions that could be suggested.Here's one way looping through columns -
Sample input, output -
Approach #2 : Vectorized
If you have to vectorize, here's one way using
matrix-multiplication
to replace themean-reductions
and that could bring about improvements for large data -Sample output -
Approach #3 : Vectorized one more
Making use of
np.add.reduceat
to get thosemean-reductions
-Setup
Solution
If you insist on the shape you presented