如何使用 pivot 将 2 列放入 pandas 中的列多索引

How to use pivot to get 2 columns into a column multiindex in pandas

我有一个包含 4 列的数据框(a、b、c、d 是列名):

df = 
a   b   c    d
1   2   3    4
5   2   7    8

是否可以使用 df.pivot() 将 2 列放入列多索引中?以下无效:

df.pivot('a', ['b', 'c'])

我要

b  2
c  3   7
a  
1  4   NA
5  NA  8

我知道我可以使用 pivot_table 轻松完成此操作 (pd.pivot_table(df, index='a', columns=['b', 'c'])),但我很好奇 pivot 的灵​​活性,因为文档不清楚。

没有聚合的最接近的解决方案是 set_index + unstack:

df = df.set_index(['b','c','a'])['d'].unstack([0,1])
print (df)
b    2     
c    3    7
a          
1  4.0  NaN
5  NaN  8.0

pivot 的解决方案,但有点疯狂 - 需要创建 MultiIndex 和最后一个转置:

df = df.set_index(['b','c'])
df = df.pivot(columns='a')['d'].T
print (df)
b    2     
c    3    7
a          
1  4.0  NaN
5  NaN  8.0

显然缺少一些实现,我想您已经找到了。我们有解决方法,但你是对的,文档说 columns 参数可以是一个对象,但似乎没有任何作用。我相信@MaxU 和@jezrael 给了它一个很好的尝试,我们 none 似乎能够让它像文档中所说的那样工作。我称之为错误!如果其他人还没有或在我开始之前没有报告,我可能会报告。


就是说,我发现了这个,这很奇怪。我计划改为将列表传递给索引参数,然后进行转置。但是,字符串 'c''b' 被用作索引值……这根本不是我想要的。

奇怪的是这个

df.pivot(['c', 'b'], 'a', 'd')

a    1    5
b  NaN  8.0
c  4.0  NaN

此外,这看起来不错:

df.pivot('a', 'b', 'd')

b  2
a   
1  4
5  8

但这里的错误令人费解

print(df.pivot('a', ['b'], 'd'))
KeyError: 'Level b not found'

任务继续...


OP自己的回答
无视

使用pivot_table

df.pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')

df.pivot_table('d', 'a', ['b', 'c'])

b    2     
c    3    7
a          
1  4.0  NaN
5  NaN  8.0

我们也可以使用pd.crosstab:

In [80]: x
Out[80]:
   a  b  c  d
0  1  2  3  4
1  5  2  7  8

In [81]: pd.crosstab(x.a, [x.b, x.c], x.d, aggfunc='mean')
Out[81]:
b    2
c    3    7
a
1  4.0  NaN
5  NaN  8.0