Reputation: 155
I have the data frame as the following snipping:
I want to convert it to be like the following:
I use the following code:
df2_SEX_AGE=df1.pivot(index='codprg', columns=['SEX','ETA'], values='counts')
but it raises the following error KeyError: 'Level SEX not found'
Upvotes: 1
Views: 140
Reputation: 862611
For convert MultiIndex
to Index
use list comprehension with pivot_table
for avoid error:
Index contains duplicate entries, cannot reshape
df2_SEX_AGE=df1.pivot_table(index='codprg',
columns=['SEX','ETA'],
values='counts',
aggfunc='sum')
df2_SEX_AGE.columns = [f'{a}{b}' for a, b in df2_SEX_AGE.columns]
Upvotes: 1
Reputation: 27869
This should sort you out:
(df1.assign(p=df['SEX'].astype(str) + df['ETA'].astype(str))
.pivot(index='codprg', columns='p', values='counts'))
Upvotes: 1