Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas reshaping to sub-columns

I have a dataframe which has columns = [‘personName’, ‘Date’, ‘groceries’, ‘entertainment’]

with groceries and entertainment being how much that person spent in each category that day.
I am trying to reshape the data frame so that ‘Date’ becomes the top level column with ‘groceries’ and ‘entertainment’ subcolumns under each Date. Making it easier to compare spends across each category across different persons, How can I do that pls? The code below does not create the subcolumns but rather Date just repeats itself for both values.

pivoted = df(index='personName', columns=['Date'], values=['groceries', 'entertainment'])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It would be better if you provide an MRE but you can still try this :

pivoted = df.pivot(index='personName', columns=['Date'], values=['groceries', 'entertainment'])

out = pivoted.swaplevel(axis=1).sort_index(axis=1) # <-- add this line to level-up/sort the dates

Or, in its chained version :

out = (
    df.pivot(
        index='personName',
        columns=['Date'],
        values=['groceries', 'entertainment'])
    .swaplevel(axis=1).sort_index(axis=1)
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading