简体   繁体   中英

Transpose only one level of a pandas MultiIndex dataFrame

I am trying to reformat a DataFrame, turning values in a row into columns. I tried using melt but just got errors. Transpose seemed to get me part of the way there, but gave weird output (because the input was a grouped DataFrame I think)

d = {'name':['bil','bil','bil','jim'],
     'col2': ['acct','law', 'acct2','law'],
     'col3': [1,2,3,55]
    }
df2 = pd.DataFrame(data=d)

df2.groupby(['name','col2']).agg({'col3':'first'})

OUTPUT:

name    col2      col3
bil     acct        1
        acct2       3
        law         2
jim     law        55

GOAL:

     acct acct2 law
bill 1     3     2
jim              55

You can use first directly. Also, you'll need unstack with a custom fill_value :

(df2.groupby(['name', 'col2'])['col3']
    .first()
    .unstack(fill_value='')
    .rename_axis(None, 1))

     acct acct2 law
name               
bil     1     3   2
jim              55

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM