我有两个数据帧。我目前有下面的代码,但我现在知道如何在dataframe 2中搜索客户ID,将数量放入相应的product列中
Dataframe 1 (INPUT DF):
CustomerID Product Quantity
123 Ball 2
123 Leash 2
456 Ball 1
Dataframe 2 (OUTPUT DF):
CustomerID Ball Leash
123 0 0
456 0 0
我希望他们看起来像这样
Dataframe 1 (INPUT):
CustomerID Product Quantity
123 Ball 2
123 Leash 2
456 Ball 1
Dataframe 2 (OUTPUT):
CustomerID Ball Leash
123 2 2
456 1 0
如果我需要进一步解释,请告诉我
### Adding how many for each customer
for index, row in df2.iterrows():
ID = row["Customer_ID"]
Product = row["Product_Name"]
Quantity = row["Quantity"]
df.loc[df.index[df[ID]], Product] = Quantity
我想你在找df.pivot。从熊猫文档:
在案例中使用pivot会在索引中生成CustomerID,在列中生成Product:
然后可以使用^{} 在剩余的单元格中获取0
如果我理解正确,您希望输入来自df1的每个用户的每个产品的计数,我将从df1本身生成:
输出
相关问题 更多 >
编程相关推荐