首页 > 解决方案 > Python 3:pandas 组多索引和每个多索引 2 个单独列的平均值

问题描述

我需要什么代码来mean按类型在每个会话中执行药物和健康。

在此处输入图像描述

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

这些都是当前的列。我虽然它应该被session(first) 和 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

如何更正此代码以使其正常工作:每次会话和按类型获取药物和健康的平均值?

标签: pythonpandas

解决方案


IIUC,试试这个:

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

推荐阅读