简体   繁体   中英

Pandas dataframe average calculation

I have a dataframe that I would like to compute the average across columns. I have the following dataframe:

数据框

Column 'A' repeats but not column 'B'. I would like to compute the average of the values in column 'B' for the repeating numbers in column 'A'. For example for the first value in column 'A' which is 1 the value in 'B' is 3 and the next value in column 'A' which is 1 the value in 'B' is 9 and the next is 4 and so on. Then continue with 2 and 3 etc...

I was thinking that if I can move those values to columns then compute the average across columns it would be easier but I can't find a way to copy the values there. Maybe there is an easier way?

This is what I would like :

DF2

You can use groupby and mean()

df.groupby('A').B.mean()

As @fuglede mentioned

df.groupby('A').mean()

would work as well as there is only column B left for aggregation. Either way you get

A
1    6.25
2    6.50
3    4.75

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM