I have a 2d array/pandas data frame like below:
          a         b         c
0    (1, 2)    (4, 4)  (10, 12)
1  (11, 10)  (44, 44)    (5, 6)
I would like to find out the row average in tuple form. the desired output would be:
          a         b         c       avg
0    (1, 2)    (4, 4)  (10, 12)    (5, 6)
1  (11, 10)  (44, 44)    (5, 6)  (20, 20)
thanks
One way using apply inspired from https://stackoverflow.com/questions/12412546/average-tuple-of-tuples
df['avg'] = df.apply(lambda x: tuple(map(np.mean, zip(*x))),axis=1)
Another alternative:
df.apply(lambda x: pd.DataFrame(x.tolist()).mean().round().agg(tuple),axis=1)
0      (5.0, 6.0)
1    (20.0, 20.0)
Or even better:
s  = df.stack()
df['avg'] = pd.DataFrame(s.tolist(),s.index).mean(level=0).round().agg(tuple,1)
print(df)
          a         b         c           avg
0    (1, 2)    (3, 4)  (10, 11)    (5.0, 6.0)
1  (12, 10)  (44, 44)    (5, 6)  (20.0, 20.0)
                        I will do map for twice 
list(map(lambda x : tuple(map(np.mean, zip(*x))), df.values.tolist()))
[(4.666666666666667, 5.666666666666667), (20.333333333333332, 20.0)]
                        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