简体   繁体   English

Python Pandas-如何解开具有两个值的数据透视表,每个值变成一个新列?

[英]Python Pandas- how to unstack a pivot table with two values with each value becoming a new column?

After pivoting a dataframe with two values like below: 在使用以下两个值旋转数据框后:

import pandas as pd

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                       'foo', 'bar', 'foo', 'bar'],
            'B' : ['one', 'one', 'two', 'two',
                      'two', 'two', 'one', 'two'],
            'C' : [56, 2, 3, 4, 5, 6, 0, 2],
            'D' : [51, 2, 3, 4, 5, 6, 0, 2]})

pd.pivot_table(df, values=['C','D'],rows='B',cols='A').unstack().reset_index()

When I unstack the pivot and reset the index two new columns 'level_0' and 0 are created. 当我拆开数据透视图并重置索引时,将创建两个新列“ level_0”和0。 Level_0 contains the column names C and D and 0 contains the values. Level_0包含列名C和D,0包含值。

    level_0     A   B   0
0   C   bar     one     2.0
1   C   bar     two     4.0
2   C   foo     one     28.0
3   C   foo     two     4.0
4   D   bar     one     2.0
5   D   bar     two     4.0
6   D   foo     one     25.5
7   D   foo     two     4.0

Is it possible to unstack the frame so each value (C,D) appears in a separate column or do I have to split and concatenate the frame to achieve this? 是否可以拆开框架,使每个值(C,D)出现在单独的列中,或者我必须拆分并连接框架才能实现此目的? Thanks. 谢谢。

edited to show desired output: 编辑以显示所需的输出:

    A   B   C   D
0   bar one 2   2
1   bar two 4   4
2   foo one 28  25.5
3   foo two 4   4

You want to stack (and not unstack): 您要stack (而不是堆叠):

In [70]: pd.pivot_table(df, values=['C','D'],rows='B',cols='A').stack()
Out[70]: 
          C     D
B   A            
one bar   2   2.0
    foo  28  25.5
two bar   4   4.0
    foo   4   4.0

Although the unstack you used did a 'stack' operation because you had no MultiIndex in the index axis (only in the column axis). 虽然unstack你使用做了一个“堆”操作,因为你在指数线(仅在列轴)无多指标。

But actually, you can get there also (and I think more logical) with a groupby-operation , as this is what you actually do (group columns C and D by A and B): 但是实际上,您还可以通过groupby-operation到达那里(并且我认为更合乎逻辑),因为这是您实际上所做的(将C和D列按A和B分组):

In [72]: df.groupby(['A', 'B']).mean()
Out[72]: 
          C     D
A   B            
bar one   2   2.0
    two   4   4.0
foo one  28  25.5
    two   4   4.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM