将项目与来自其他列的值相关联。

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月1日 20:40:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定