据我了解,您的数据框包含买家 ID 列表、他们购买的产品以及他们购买的数量。您想了解每个客户负责购买的每种产品占总购买量的百分比。
例如,如果买家 1 购买了所有 A,那么他们将 100%,如果买家 2 购买了所有 B 的一半,那么他们将是 50%。
每个买家一次只购买一种产品。
我生成了一个数据集来复制它:
options = 'ABCDEF'
product = []
count = []
buyer = []
for i in range(0,100):
product.append(test[np.random.randint(0,5)])
count.append(np.random.randint(0,10))
buyer.append(i)
df = pd.DataFrame(data = [buyer, product, count]).transpose()
df.columns = ['buyer','product','count']
print(df.head())
>>> buyer product count
0 0 B 4
1 1 B 6
2 2 A 2
3 3 D 2
4 4 D 5
为了计算每个客户的百分比,您需要购买每种产品的总数
totals = {'A' : 0,
'B' : 0,
'C' : 0,
'D' : 0,
'E' : 0,
'F' : 0}
for i in range(0, len(df)):
currentProduct = df.iloc[i,1]
totals[currentProduct] = totals[currentProduct] + 1
现在您需要做的就是计算每个产品的计数/总数并保存到数据框中的新列。
for i in range(0, len(df)): # Iterate over every row in
# new column | count bought | total bought by all
df.iloc[i,3] = df['count'][i]/totals[df['product'][i]]
print(df.head())
>>> buyer product count contribution
0 0 B 4 0.210526
1 1 B 6 0.315789
2 2 A 2 0.080000
3 3 D 2 0.111111
4 4 D 5 0.277778
print(totals)
>>> {'A': 25, 'B': 19, 'C': 15, 'D': 18, 'E': 23, 'F': 0}
我知道这与您使用的方法不同,但它应该仍然有效,如果您愿意,请发布您的代码示例以便我们查看错误,或者只需勾选此答案并更改标题以表示已回答的问题.
如果我误解了什么就这么说