Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row average of tuples in data frame / 2d array

Tags:

python

pandas

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

like image 686
kt_at_kt Avatar asked Nov 28 '22 19:11

kt_at_kt


2 Answers

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)
like image 67
anky Avatar answered Dec 20 '22 03:12

anky


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)]
like image 24
BENY Avatar answered Dec 20 '22 01:12

BENY