所以我有一个 Pandas DataFrame,其中包含每月买家和卖家之间的互动的面板数据:
Buyer Seller Month Amount Amounttotal
0 Buyer1 Seller1 2009-07-31 00:00:00 10 255
1 Buyer1 Seller2 2009-07-31 00:00:00 15 255
2 Buyer1 Seller3 2009-07-31 00:00:00 120 255
3 Buyer1 Seller4 2009-07-31 00:00:00 110 255
4 Buyer1 Seller1 2009-08-31 00:00:00 5 427
5 Buyer1 Seller2 2009-08-31 00:00:00 12 427
6 Buyer1 Seller3 2009-08-31 00:00:00 20 427
7 Buyer1 Seller4 2009-08-31 00:00:00 180 427
8 Buyer1 Seller5 2009-08-31 00:00:00 210 427
我有多个卖家的最大数据,例如 Buyer1,Buyer2,Buyer3 等。Amountttotal 是 buyer1 在该月内总共购买的金额。我正在计算,对于每个月的每个买家,它是 3 公司 HHI,这意味着从买家的三个最大交互中找到每月总交易量百分比的平方值的总和。在上面的例子中,对于 2009 年的 3 公司 HHI-42
只需获取 Amount 列,对其进行排序,然后获取前 3 个元素。而且您甚至不需要总量列,因为您可以对 Amount 列进行求和。
def compute_hhi(buyer_month):
total = float(buyer_month['Amount'].sum())
top_3_amts = buyer_month['Amount'].order(ascending = False)[0:3]
hhi_elements = [(value/total)**2 for value in top_3_amts]
hhi = sum(hhi_elements)
return hhi
grouped = df.groupby(['Buyer','Month'])
hhis = grouped.apply(compute_hhi)
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(72条)