【问题标题】:Market basket analysis in pythonpython中的购物篮分析
【发布时间】:2020-04-08 22:39:16
【问题描述】:

我正在对一家鞋店的 xlsx 数据集进行购物篮分析 我的数据集就像

收据ID |物品名称 |类别 |净数量

123 |黑鞋 |鞋 | 5

123 |棕色鞋 |鞋 | 4

125 |凉鞋 |凉鞋 | 2

125 |白沙瓦里 |鞋 | 1

我希望我的数据像

收据ID |物品名称 |类别 |净数量

123 |黑鞋,棕鞋 |鞋 | 9

125 |凉鞋,白沙瓦里 |凉鞋、鞋| 3

def new_list(items): 
   Row_list=[ ] 
   for rows in items.ReceiptID: 
     if items.ReceiptD==ReceiptID-1: 
       my_list=[items.ItemName] 
       Row_list.append(my_list) 
     return(Row_list) 

如果我在其中加载数据框,我想要一个 python 函数来执行此操作。 谢谢:)

【问题讨论】:

  • 您介意向我们展示您目前取得的成就吗?
  • def new_list(items): Row_list=[ ] 用于 items.ReceiptID: if items.ReceiptD==ReceiptID-1: my_list=[items.ItemName] Row_list.append(my_list) return(行列表)
  • 这个功能不起作用,我不知道如何使它起作用
  • @HammadIqbal 请用代码更新问题,而不是把它放在评论中——很难按原样阅读。
  • 更新!!!!!!!!!

标签: python market-basket-analysis


【解决方案1】:

IIUC 你只需要groupby + agg 如下

df = pd.DataFrame({"ReceiptID": [123,123,125,125],
                   "ItemName": ["Black Shoe", "Broen Shoe", "Sandal", "Peshawari"],
                   "Category": ["Shoes", "Shoes", "Sandal" ,"Shoes"],
                   "NetQty": [5,4,2,1]})


out = df.groupby("ReceiptID")\
        .agg({"ItemName":"unique",
              "Category":"unique",
              "NetQty":"sum"})\
        .reset_index()
   ReceiptID                  ItemName         Category  NetQty
0        123  [Black Shoe, Broen Shoe]          [Shoes]       9
1        125       [Sandal, Peshawari]  [Sandal, Shoes]       3

如果你只想要字符串而不是列表,你可以添加这两行

for col in ["ItemName", "Category"]:
    out[col] = out[col].str.join(", ")
   ReceiptID                ItemName       Category  NetQty
0        123  Black Shoe, Broen Shoe          Shoes       9
1        125       Sandal, Peshawari  Sandal, Shoes       3

【讨论】:

    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多