1

How can I apply pandas.pivot_table to the dataframe:

df = pd.DataFrame(
[
    {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col1', 'colvalue': 'sfjdka'},
    {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col2', 'colvalue': 25},
    {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col1', 'colvalue': 'laksjd'},
    {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col2', 'colvalue': 26}
]

)

to get a multi-indexed result (indexed by o1_pkid and o2_pkid), where the columns come from colname and the values come from colvalue? I am looking to get a result something like:

colname                 col1          col2
o1_pkid      o2_pkid 
645          897      'sfjdka'      25
             159      'laksjd'      26

1 Answer 1

1

Use set_index + unstack:

df = df.set_index(['o1_pkid', 'o2_pkid', 'colname'])['colvalue'].unstack()

print (df)
colname            col1 col2
o1_pkid o2_pkid             
645     159      laksjd   26
        897      sfjdka   25

But if get error:

ValueError: Index contains duplicate entries, cannot reshape

need:

pivot_table with some aggregate function like sum:

df = pd.DataFrame(
[
    {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col1', 'colvalue': 'sfjdka'},
    {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col2', 'colvalue': 25},
    {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col1', 'colvalue': 'laksjd'},
    {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col2', 'colvalue': 10},
    {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col2', 'colvalue': 26}
])


df = df.pivot_table(index=['o1_pkid', 'o2_pkid'], 
                        columns='colname', 
                        values='colvalue', 
                        aggfunc='sum')
print (df)
colname            col1 col2
o1_pkid o2_pkid             
645     159      laksjd   36
        897      sfjdka   25

or groupby + aggregate function + unstack:

df = df.groupby(['o1_pkid', 'o2_pkid', 'colname'])['colvalue'].sum().unstack()

print (df)
colname            col1 col2
o1_pkid o2_pkid             
645     159      laksjd   36
        897      sfjdka   25
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.