Oblomov
Oblomov

Reputation: 9665

Aggregate over groups of columns

Based on the data frame

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(2, 6)), columns=list('ABCDEF'))
print(df)
   A   B   C   D   E   F
0  82  63  71  74  71  27
1  90   9  74  35  38  43

how can I calculate the mean for each disjoint group of three columns, such that the resulting data frame looks like

   meanABC meanDEF
0  72      57.33
1  57.66   38.66 

?

Upvotes: 2

Views: 35

Answers (2)

Shishir Naresh
Shishir Naresh

Reputation: 763

try the below hope this helps:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(2, 6)), columns=list('ABCDEF'))
print(df)

Ouput will be :

    A   B   C   D   E   F
0   2  89  68  48  13  17
1  43   9  98   9  18  94

Now follow the steps:

columns = list(df.columns)
new_df = pd.DataFrame()
for i in range(0,len(columns),3):
    new_df['mean'+"".join(columns[i:i+3])] = df[columns[i:i+3]].mean(axis=1)

Ouput will be :

    meanABC     meanDEF
0   53.0    26.000000
1   50.0    40.333333

Upvotes: 2

jezrael
jezrael

Reputation: 863751

Idea is create MultiIndex first, then get new columns names for rename and last is possible use mean by second level of MultiIndex:

np.random.seed(2019)
df = pd.DataFrame(np.random.randint(0,100,size=(2, 6)), columns=list('ABCDEF'))
print(df)
    A   B   C   D   E   F
0  72  31  37  88  62  24
1  29  15  12  16  48  71

df.columns = [df.columns, np.arange(len(df.columns)) // 3]

c = 'mean' + df.columns.to_frame().groupby(1)[0].apply(''.join)
print (c)
1
0    meanABC
1    meanDEF
Name: 0, dtype: object

df = df.mean(axis=1, level=1).rename(columns=c)
print (df)
     meanABC  meanDEF
0  46.666667     58.0
1  18.666667     45.0

Upvotes: 2

Related Questions