0

I have a dataset(code below)- that looks like below -

enter image description here

d = pd.DataFrame({
    'Year': [
        2019,
        2020,
        2021,
        2022,
        2019,
        2020,
        2020,
        2021,
        2019,
        2020,
        2021,
        2022

    ],
    'Category': [
        'Salary',
        'Salary',
        'Salary',
        'Salary',
        'Misc',
        'Misc',
        'Misc',
        'Misc',
        'Bonus',
        'Bonus',
        'Bonus',
        'Bonus',

    ],
    'Amount': [
        53,
        455,
        123,
        125,
        313,
        545,
        595,
        775,
        567,
        657,
        567,
        547

    ]
})

I want to transform it to something like below -

enter image description here

Is there a pythonic way to achieve this - apart from getting unique 'Category', transposing it and then looping over Amount column to find the corresponding amount? It is not a exact transpose or group by but something similar to that.

Swapnil
  • 25
  • 1
  • 9
  • Your example table is not complete which makes your question ambiguous. But, it seems that pandas data frame + pivot_table may meet your need. – prony May 07 '20 at 02:22
  • 1
    Actually, you dont need pivot. Run this: d.set_index(["Year","Category"]).unstack("Category") Make sure that you correct the double 2020 for Misc. I would write a detail answer to explain the code but they closed the question. – prony May 07 '20 at 02:35

0 Answers0