gpt4 book ai didi

python - 在 python 中使用 pandas 合并行数据

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:57 25 4
gpt4 key购买 nike

我正在尝试编写一个小型 python 应用程序,它创建一个包含配方系统数据的 csv 文件,

想象一下excel数据的如下结构

Manufacturer    Product Data 1  Data 2  Data 3
Test 1 Product 1 1 2 3
Test 1 Product 2 4 5 6
Test 2 Product 1 1 2 3
Test 3 Product 1 1 2 3
Test 3 Product 1 4 5 6
Test 3 Product 1 7 8 9

合并后我希望数据以下列格式显示,

Test 1  Product 1   1   2   3   0   0   0   0   0   0
Test 2 Product 2 4 5 6 0 0 0 0 0 0
Test 2 Product 1 1 2 3 0 0 0 0 0 0
Test 3 Product 1 1 2 3 4 5 6 7 8 9

非常感谢任何帮助,到目前为止我可以读取 Pandas 数据集并转换为 CSV

问候李

最佳答案

使用 melt、groupby、pd.Series 和 unstack:

(df.melt(['Manufacturer','Product'])
.groupby(['Manufacturer','Product'])['value']
.apply(lambda x: pd.Series(x.tolist()))
.unstack(fill_value=0)
.reset_index())

输出:

  Manufacturer    Product  0  1  2  3  4  5  6  7  8
0 Test 1 Product 1 1 2 3 0 0 0 0 0 0
1 Test 1 Product 2 4 5 6 0 0 0 0 0 0
2 Test 2 Product 1 1 2 3 0 0 0 0 0 0
3 Test 3 Product 1 1 4 7 2 5 8 3 6 9

关于python - 在 python 中使用 pandas 合并行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50471064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com