Home > Net >  Pandas crosstab how can i get two values of mean aggregation
Pandas crosstab how can i get two values of mean aggregation

Time:02-02

Here is my problem. Suppose I have

df = ({'DAY':['20210101','20210102','20210102'],'TTM':[0.1,0.1,0.5],'TTS':[0.3,0.4,0.4] })

I want to get a CROSSTAB that calculates the mean of TTM and TTS group by DAY, like this

DAY      |meanTTM |MeanTTS
20210101 | 0.1    |0.3
20210102 | 0.3    | 0.4

I tried

pd.crosstab(index=data3['DAY'],columns=df['DAY'],values=df['TPS_ATTENTE','TPS_GEN_ACK'],margins=False,aggfunc='mean')

But I don't get any result, can anyone help?

CodePudding user response:

You can use groupby_mean:

out = df.groupby('DAY')[['TTM','TTS']].mean().add_prefix('mean').reset_index()

Output:

        DAY  meanTTM  meanTTS
0  20210101      0.1      0.3
1  20210102      0.3      0.4

CodePudding user response:

You can create a pivot table

pd.pivot_table(df, index='DAY')

The default aggregation function is mean but this can be changed with the aggfunc parameter.

  •  Tags:  
  • Related