英文:
Item to column with value from other column
问题
如何在Python中将DataFrame从这种格式:
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 |
转换成这种格式:
date | HTA-01 | HTA-02 | HTB-07 |
---|---|---|---|
2023-01-01 | 16 | 29 | 1 |
2023-01-02 | 18 | 34 | nan |
每个唯一的item_code值都成为一列,其值来自qty列。以下是示例数据:
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)
英文:
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)
答案1
得分: 1
使用 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')
#输出
# qty
#item_code HTA-01 HTA-02 HTB-07
#date
#2023-01-01 16 29 1
#2023-01-02 18 34 NaN
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论