python - 在 DataFrame 的开头添加多索引摘要列

标签 python pandas multi-index summary

如果我有一个数据框并且我想在开头插入一个摘要列,我可以运行

df.insert(0, 'Average', df.mean(axis='columns')) 

假设我有一个以下形式的多索引数据框

df = pd.DataFrame()
for l1 in ('a', 'b'):
    for l2 in ('one', 'two'):
        df[l1, l2] = np.random.random(size=5)
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['L1', 'L2'])

L1         a                   b          
L2       one       two       one       two
0   0.585409  0.563870  0.535770  0.868020
1   0.404546  0.102884  0.254945  0.362751
2   0.475362  0.601632  0.476761  0.665126 
3   0.926288  0.615655  0.257977  0.668778
4   0.509069  0.706685  0.355842  0.891862

如何将所有 one 列和所有 two 列的平均值添加到此 DataFrame 的前两列,并将其称为“平均值”

编辑: 预期输出为 df.mean(level=1, axis=1) ,但使用 L1 标签“Average”插入到帧的前两列中。我希望以下内容能够发挥作用:

df.insert(0, 'Average', df.mean(level=1, axis=1))

最佳答案

IIUC,您只需要groupby来计算平均值,然后对结果系列的列进行一些处理:

s = df.groupby(level=1, axis=1).mean()
s.columns = pd.MultiIndex.from_product([['Average'], s.columns])
pd.concat([s, df], 1)

    Average                   a                   b
        one       two       one       two       one       two
0  0.517939  0.713116  0.531990  0.578338  0.503889  0.847894
1  0.571197  0.676809  0.698986  0.425227  0.443409  0.928391
2  0.689653  0.399053  0.843179  0.069174  0.536126  0.728931
3  0.288367  0.197891  0.026974  0.026774  0.549761  0.369009
4  0.449904  0.590919  0.372560  0.556332  0.527247  0.625506

关于python - 在 DataFrame 的开头添加多索引摘要列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451146/

相关文章:

python - 在 Pandas Groupby 中使用列和行多索引值,无需拆栈

python - IndexError:用作索引的数组在python中必须为整数(或 bool 值)类型

python - 暂停调用的函数几秒钟

python - 如何根据 Python 中另一个数据框的关系为变量赋值

python - Pandas ParserError : Error tokenizing data. C 错误:字符串内的 EOF

python - 从 csv 普查数据创建多索引

python - 将 pandas 数据框中的二级索引重置为从 1 开始

python - 在 OS X Lion 的 pycharm 中使用 emacs 绑定(bind)

python - 无法通过 python-jira lib 连接到 JIRA-api

python - 更改 pandas 数据帧多重索引中的值