irriss
irriss

Reputation: 782

Create columns from index values

Let say I have my data shaped as in this example

idx = pd.MultiIndex.from_product([[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']],
                                 names=['numbers', 'letters'])
col = ['Value']

df = pd.DataFrame(list(range(18)), idx, col)

print(df.unstack())

The output will be

            Value        
letters     a   b   c
numbers              
1           0   1   2
2           3   4   5
3           6   7   8
4           9  10  11
5          12  13  14
6          15  16  17

letters and numbers are indexes and Value is the only column

The question is how can I replace Value column with columns named as values of index letters?

So I would like to get such output

numbers     a   b   c         
1           0   1   2
2           3   4   5
3           6   7   8
4           9  10  11
5          12  13  14
6          15  16  17

where a, b and c are columns and numbers is the only index.

Appreciate your help.

Upvotes: 1

Views: 77

Answers (2)

KenHBS
KenHBS

Reputation: 7164

Wen-Ben's answer prevents you from running into a data frame with multiple column levels in the first place.

If you happened to be stuck with a multi-index column anyway, you can get rid of it by using .droplevel():

df = df.unstack()
df.columns = df.columns.droplevel()

df

Out[7]: 
letters   a   b   c
numbers            
1         0   1   2
2         3   4   5
3         6   7   8
4         9  10  11
5        12  13  14
6        15  16  17

Upvotes: 1

BENY
BENY

Reputation: 323276

The problem is caused by you are using unstack with DataFrame, not pd.Series

df.Value.unstack().rename_axis(None,1)
Out[151]: 
          a   b   c
numbers            
1         0   1   2
2         3   4   5
3         6   7   8
4         9  10  11
5        12  13  14
6        15  16  17

Upvotes: 4

Related Questions