0

How to change dataframe like this

date item_code qty
2023-01-01 HTA-01 16
2023-01-01 HTA-02 29
2023-01-01 HTB-07 1
2023-01-02 HTA-01 18
2023-01-02 HTA-02 34

to this in python

date HTA-01 HTA-02 HTB-07
2023-01-01 16 29 1
2023-01-02 18 34 nan

Each unique value from item_code become column. The value from its is from qty column. This is sample data to try

data = { 'date': ['2023-01-01','2023-01-01','2023-01-01','2023-01-02', '2023-01-02'],
'item_code':['HTA-01', 'HTA-02', 'HTB-07', 'HTA-01', 'HTA-02'],
'qty':['16', '29', '1', '18', '34'],
}
df = pd.DataFrame(data2)
Herza Ryo
  • 43
  • 5

1 Answers1

1

Use pivot:

data = { 'date': ['2023-01-01','2023-01-01','2023-01-01','2023-01-02', '2023-01-02'],
'item_code':['HTA-01', 'HTA-02', 'HTB-07', 'HTA-01', 'HTA-02'],
'qty':['16', '29', '1', '18', '34'],
}
df = pd.DataFrame(data)

df.pivot(index='date', columns='item_code')
#Output
#              qty              
#item_code  HTA-01 HTA-02 HTB-07
#date                           
#2023-01-01     16     29      1
#2023-01-02     18     34    NaN
Pep_8_Guardiola
  • 5,002
  • 1
  • 24
  • 35
  • 1
    Please don't answer duplicate questions. Instead [vote to close](https://stackoverflow.com/help/privileges/close-questions), since you have the required reputation. – BigBen Jun 01 '23 at 12:46