python - 在 Pandas DataFrame 中转置选定的 MultiIndex 级别

标签 python pandas multi-index

我有一个多索引数据框:

import pandas as pd
import numpy as np

l0, l1 = ['A', 'B'],['a', 'b']
c0 = ['c1', 'c2', 'c3']
data = np.arange(12).reshape(4,3)
df = pd.DataFrame(data=data, 
                  index=pd.MultiIndex.from_product([l0,l1]),
                  columns=c0)

>>>
     c1  c2  c3
A a   0   1   2
  b   3   4   5
B a   6   7   8
  b   9  10  11

我想转置 MultiIndex 和列的一个级别,以便我得到:

df2 = pd.DataFrame(index=pd.MultiIndex.from_product([l0, c0]),
                   columns=l1)

>>>
    a    b
A c1  NaN  NaN
  c2  NaN  NaN
  c3  NaN  NaN
B c1  NaN  NaN
  c2  NaN  NaN
  c3  NaN  NaN

显然我想填充正确的值。我的解决方案目前是将 map 与迭代器一起使用,但感觉 Pandas 会有一些 native 的方式来执行此操作。我说的对吗,还有更好(更快)的方法吗?

from itertools import product
def f(df, df2, idx_1, col_0):
    df2.loc[(slice(None), col_0), idx_1] = \
        df.loc[(slice(None), idx_1), col_0].values
m = map(lambda k: f(df, df2, k[0], k[1]), product(l1, c0))
list(m) # <- to execute

>>> df2
>>>
      a   b
A c1  0   3
  c2  1   4
  c3  2   5
B c1  6   9
  c2  7  10
  c3  8  11

最佳答案

首先堆叠列,然后取消堆叠您想要成为新列的级别:

df.stack().unstack(level=1)
Out: 
      a   b
A c1  0   3
  c2  1   4
  c3  2   5
B c1  6   9
  c2  7  10
  c3  8  11

关于python - 在 Pandas DataFrame 中转置选定的 MultiIndex 级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566616/

相关文章:

python - 如何自动点击 "Content"按钮

excel - xlwings 与 pandas 本地导出与多索引数据帧 : how to reconcile?

python - Multiindex 中的 Pandas 自定义排序行

python - 如何从 aiohttp.web 服务器返回重定向响应

python - 选择相关 选定相关

python - 获取数据框中字典的长度

python-3.x - 我无法按列值过滤数据框

python - 如何在Python中将列标题设置为副标题

python - PyTorch:时间序列任务的数据加载器

python - 如何在 pandas.multiindex 级别应用条件?