python - Groupby 作为具有 MultiIndex 的列

标签 python pandas pandas-groupby multi-index

我有一个类似于的数据框

df = pd.DataFrame(
    pd.np.random.randint(1, 10, (20, 2)),
    index=["a", "b", "c", "d"] * 5,
    columns=["foo", "bar"],
)

看起来像这样

df

我试图将其转换为以下多索引形式:4 个轴标签中的每一个都有两列,每个标签都有一个“foo”和“bar”子列:

df-target

我尝试摆弄df.groupby(df.index),但后来我不知道如何将组变成列。

最佳答案

使用GroupBy.cumcount对于索引 DataFrame.set_index 中的 MultiIndex ,然后通过 DataFrame.unstack reshape 形状并将列中 Multiindex 的顺序更改为 DataFrame.swaplevelDataFrame.sort_index :

df1 = (df.set_index(df.groupby(level=0).cumcount(), append=True)
         .unstack(0)
         .swaplevel(0,1, axis=1)
         .sort_index(axis=1, level=[0,1], ascending=[True, False]))
print (df1)
    a       b       c       d    
  foo bar foo bar foo bar foo bar
0   6   8   1   6   8   4   6   1
1   2   6   4   5   3   1   5   4
2   2   5   2   9   5   4   8   9
3   5   2   6   6   7   3   2   9
4   4   8   9   6   4   2   1   5

关于python - Groupby 作为具有 MultiIndex 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57338402/

相关文章:

python - 从 Python 中的 PrivateKey/CertificateRequest/Certificate 中提取公钥模数,格式与 OpenSSL 相同

python - 将表(几页)抓取到 Pandas Dataframe

python - 在 pandas DataFrame 列中存储列表

python - Pandas groupby 与 lambda 并在列表中

python - Pandas:如何在 groupby 对象上使用自定义应用函数返回多列

python - 是否有可能用纯 Python 编写与魔兽世界一样大的 3D 游戏?

python - 当在循环外调用该变量时,如何获取 for 循环内变量的所有值? (不使用 list.append ( ))

python - 设置在 macOS 上使用 pip 安装 unicorn 的库路径(缺少 libunicorn.dylib)

python - 使用日期透视 pandas 数据框并显示每个日期的计数

python - 每小时直方图 - matplotlib