简体   繁体   中英

Python 3: pandas group multiindex and mean of 2 separate columns per multiindex

What code do I need to perform a mean of both drugs and health per session by type.

在此处输入图像描述

df[['drugs', 'health', 'session', 'type']]

these all are currently columns. I though it ought to be indexed by both session (first) and then type .

grouped_S = grouped['session'].as_index=True
grouped_c = grouped['type'].as_index=True
grouped_dh = grouped['drugs', 'health'].mean().as_index=False

How do I correct this code to make it work: getting an average of drugs and health per session and by type?

IIUC, try this:

df.groupby(['session', 'type'])[['drugs', 'health']].mean()

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