Home > Backend Development > Python Tutorial > How to Calculate Average Values with Multiple Groupings in Pandas?

How to Calculate Average Values with Multiple Groupings in Pandas?

Mary-Kate Olsen
Release: 2024-11-20 01:45:01
Original
357 people have browsed it

How to Calculate Average Values with Multiple Groupings in Pandas?

Group-by Aggregation with Multiple Groupings and Average

In Pandas, performing aggregations on data grouped by multiple levels is a common operation. Consider the following DataFrame:

   cluster  org      time
   1      a       8
   1      a       6
   2      h       34
   1      c       23
   2      d       74
   3      w       6 
Copy after login

A common task is to calculate the average of a given column, such as "time," per group defined by multiple variables, such as "cluster" and "org."

Solution 1: Mean on Cluster Groupings Only

To compute the mean of "time" grouped by "cluster" only, you can use the following code:

df.groupby(['cluster']).mean()
Copy after login

Result:

              time
cluster
1        12.333333
2        54.000000
3         6.000000
Copy after login

Solution 2: Mean on a Combination of Groupings

If you want to calculate the mean of "time" for each combination of "cluster" and "org," you can use:

df.groupby(['cluster', 'org']).mean()
Copy after login

Result:

               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6
Copy after login

Solution 3: Nested Mean on Groupings

To perform a nested mean, first averaging on the combination of "cluster" and "org" and then averaging on "cluster" groups, use:

(df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Copy after login

Result:

cluster  mean(time)
1          15 #=((8 + 6) / 2 + 23) / 2
2          54 #=(74 + 34) / 2
3           6
Copy after login

The above is the detailed content of How to Calculate Average Values with Multiple Groupings in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template