0

I have the following pandas dataframe:

import pandas as pd

df = pd.DataFrame([[1, 100, 300, 250], 
                   [2, 475, 200, 0], 
                   [3, 125, 365, 100]], columns=['Client_ID', 'Purchase 1', 'Purchase 2', 'Purchase 3'])

╔═══════════╦════════════╦════════════╦════════════╗
║ Client_ID ║ Purchase 1 ║ Purchase 2 ║ Purchase 3 ║
╠═══════════╬════════════╬════════════╬════════════╣
║         1 ║        100 ║        300 ║        250 ║
║         2 ║        475 ║        200 ║          0 ║
║         3 ║        125 ║        365 ║        100 ║
╚═══════════╩════════════╩════════════╩════════════╝

I want to transpose that table as follows:

╔═══════════╦═══════════╗
║ Client_ID ║ Purchases ║
╠═══════════╬═══════════╣
║         1 ║       100 ║
║         1 ║       300 ║
║         1 ║       250 ║
║         2 ║       475 ║
║         2 ║       200 ║
║         2 ║         0 ║
║         3 ║       125 ║
║         3 ║       365 ║
║         3 ║       100 ║
╚═══════════╩═══════════╝

I've tried df.T but didn't work and I don't want to use a for loop. Is there a way to acchieve this?

Snedecor
  • 689
  • 1
  • 6
  • 14

1 Answers1

2

You can do:

df.melt('Client_ID', value_name='Purchases').set_index('Client_ID').sort_index().drop('variable', axis=1)

Giving:

           Purchases
Client_ID           
1                100
1                300
1                250
2                475
2                200
2                  0
3                125
3                365
3                100
Tom
  • 8,310
  • 2
  • 16
  • 36