0

I have a data frame that needs to be converted like so below. I would like to convert the headers accts into their own values in rows while keeping accts grouped together in the "Acct" Column. Understand that melt could achieve this but I am having trouble applying even when reading docs and examples. Help would be much appreciated.

Setup:

df = pd.DataFrame({'Year': {0: 2022, 1: 2023, 2: 2024},
                   'Acct 1': {0: 100, 1: 300, 2: 500},
                   'Acct 2': {0: 200, 1: 400, 2: 600}})

df

Output:

df = pd.DataFrame({'Year': {0: 2022, 1: 2023, 2: 2024, 3:2022, 4:2023, 5:2024},
                   'Acct': {0: 'Acct 1', 1: 'Acct 1', 2: 'Acct 1', 3: 'Acct 2', 4:'Acct 2', 5:'Acct 2'},
                   'Amount': {0: 100, 1: 300, 2: 500, 3: 200, 4: 400, 5: 600}})

df
Evan
  • 29
  • 6

1 Answers1

0

This should work

df.melt(id_vars='Year', value_vars=['Acct 1', 'Acct 2'])
ndr
  • 1,427
  • 10
  • 11