Calculating the expanding average for all columns in df pandas

My df looks like this:

    cat1     cat2     x1     x2     x3      x4      x5      x6   . . .
0    str     str    float  float   float  float   float   float  . . .
1    str     str    float  float   float  float   float   float  . . .
.     .       .       .      .       .       .       .       .   . . .
.     .       .       .      .       .       .       .       .   . . .

I tried this:

df = df.groupby(['cat1','cat2']).apply(pd.expanding_mean)

but it gives me

ValueError: could not convert string to float: 

The only lines are in the group. This works great, but I don't need:

df = df.groupby(['cat1','cat2']).mean()
+4
source share
1 answer

Thanks also for the efforts of other users, perhaps the following solution:

df.iloc[:,2:] = df.groupby(['cat1','cat2']).transform(pd.expanding_mean)

Saves the first two columns.

+2
source

Source: https://habr.com/ru/post/1606968/


All Articles