gpt4 book ai didi

python - 创建具有重复条目的数据框

转载 作者:行者123 更新时间:2023-12-01 00:41:34 26 4
gpt4 key购买 nike

我做了一个sql查询,然后用data = pd.read_sql(query, connection)我得到了下表,

  ID        ITEM   TYPE_USER   Count
711757 item1 type1 1
711757 item2 type1 1
711757 item3 type1 1
711794 item1 type2 1
711794 item2 type2 1
711541 item2 type3 1
. . . .
. . . .

但我需要创建以下数据框

   ID     item1    item2    item3      TYPE_USER
711757 1 1 1 type1
711794 1 1 0 type2
711541 0 1 0 type3

所以,我的想法是采取

`data.pivot(index='ID', columns = 'ITEM', values='Count')   

但是,这给了我以下数据框

       ID     item1    item2    item3    
0 711757 1 1 1
1 711794 1 1 0
2 711541 0 1 0

在这一点上,我不知道如何加入“TYPE_USER”列,任何想法将不胜感激!谢谢!

最佳答案

pd.pivot_table(df, index=['ID','TYPE_USER'], columns='ITEM', values='Count').fillna(0).reset_index()

结果

ITEM    ID  TYPE_USER   item1   item2   item3
0 711541 type3 0.0 1.0 0.0
1 711757 type1 1.0 1.0 1.0
2 711794 type2 1.0 1.0 0.0

关于python - 创建具有重复条目的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311750/

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