3

I have the following Series with a multi-index:

import pandas as pd
index = pd.MultiIndex(labels = [[0,1,1],[2,2,3]], levels = [[1,2],[1,2,3,4]], names = ['a','b'])
s = pd.Series(index=index, data=[100,200,300])

a  b
1  3    100
2  3    200
   4    300

I want to transform it into a DataFrame where the rows are the labels of the first index (e.g. a), the columns are the labels of the second index (e.g. b), and the values the values at index (a,b) (or None if there is none):

desired_df = pd.DataFrame(index=pd.Index(data=[1,2],name='a'), 
                          data = [[100,None],[200,300]],
                         columns = [3,4])


    3   4
a       
1   100 NaN
2   200 300.0

1 Answer 1

2

Use Series.unstack function:

print (s.unstack())
b      3      4
a              
1  100.0    NaN
2  200.0  300.0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.