Rilcon42
Rilcon42

Reputation: 9763

Explain python unstack() simply

I am trying to annotate my python code before I rewrite it to avoid unstack() because of an error. Im stumped when it comes to explaining unstack to myself, even after reading the docs and seeing the output. Can someone explain what it does without using phrases like "pivot a level"?

Definition from docs:

Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are not a MultiIndex). The level involved will automatically get sorted.

Here is the code Im attempting to annotate:

import numpy as np
import pandas as pd
from numpy.core.defchararray import add

d = {'vote': [100, 50,1,23,55,67,89,44], 
     'vote2': [10, 2,18,26,77,99,9,40], 
     'ballot1': ['a','b','a','a','b','a','c','c'],
     'voteId':[1,2,3,4,5,'aaa',7,'NaN']}
df1=pd.DataFrame(d)
#######################################################################
print(df1)
#Set the DataFrame index (row labels) using columns voteId and ballot1
s=df1[:10].set_index(['voteId','ballot1'],verify_integrity=True)
print(s)
#unstack (default -1). ?????
# s=s.unstack()
# s.columns=s.columns.map('(ballot1={0[1]}){0[0]}'.format) 
# dflw=pd.DataFrame(s)
# print(df1)
# print(dflw)

Upvotes: 1

Views: 1542

Answers (1)

John Zwinck
John Zwinck

Reputation: 249394

DataFrame.unstack() simply moves ("pivots") some of the levels of a MultiIndex (hierarchically indexed) DataFrame to become column labels instead of row labels. There are clear examples in the documentation.

Upvotes: 1

Related Questions