Skip to content Skip to sidebar Skip to footer

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']

Solution 1:

You want to stack (and not unstack):

In[70]: pd.pivot_table(df, values=['C','D'],rows='B',cols='A').stack()
Out[70]: 
          CDBAonebar22.0foo2825.5twobar44.0foo44.0

Although the unstack you used did a 'stack' operation because you had no MultiIndex in the index axis (only in the column axis).

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):

In[72]: df.groupby(['A', 'B']).mean()
Out[72]: 
          CDABbarone22.0two44.0fooone2825.5two44.0

Post a Comment for "Python Pandas- How To Unstack A Pivot Table With Two Values With Each Value Becoming A New Column?"