获取 groupby 中特定唯一名称的所有值的总和

问题描述 投票:0回答:1

我希望这是有道理的,但我需要获取一列值的总和,但它需要是与 groupby 生成的组中一个特定唯一行值关联的所有值。

这是我用来对所有内容进行分组的代码:

df_revPAR = df.groupby('IndustrySegmentName', as_index=False)[
    ['BrandRevenueTY', 'BrandSupplyTY', 'BrandDemandTY', 
     'IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']].sum()

这确实根据我想要的“IndustrySegmentName”对数据进行了分组,它给了我品牌数据的总和(每个酒店的日常数字)。这就是我需要的品牌数据信息。

问题来了。不同酒店名称的行业数据(IndustrySupplyTY、IndustryDemandTY、IndustryRevenueTY)重复。整个组 (IndustrySegementName) 的行业数据相同。这不是像“BrandSupply”或“BrandRevenue”数据这样的个人数据。我不需要获取该组中每个不同酒店的所有行的总和。我只需要行业细分名称组中酒店行业数据之一的总和,或者我需要将我从上述代码中获得的总和值除以每个 IndustrySegmentName 中分组的唯一酒店名称的数量。我该怎么做?

例如,在高档组中,我只需要从英迪格酒店获取“IndustryX”数据的总和,用作整个“高档”组的“IndustryX”数据,而不是所有值的总和在英迪格酒店和广场酒店内。

或者我需要将“高档”组中“IndustryX”数据的总和除以 2(该组中唯一酒店的数量),但我需要一种方法来获得此计数。

潜在的解决方案,但正在寻找更好的编码方式:

df_brandcount = df.groupby('IndustrySegmentName', as_index=False)[
    ['Hotel Name']].nunique()
df_revPAR['BrandCount'] = df_brandcount['Hotel Name']
python pandas dataframe group-by
1个回答
0
投票

为什么不做两个单独的分组?

因此,一个用于酒店特定数据,一个用于行业特定数据。之后您可以合并数据。

未经测试的代码,因为没有提供测试数据示例:

df_hotel = df.groupby('IndustrySegmentName', as_index=False)[
    ['BrandRevenueTY', 'BrandSupplyTY', 'BrandDemandTY', 
     'IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']].sum()
df_brand = df.groupby(['IndustrySegmentName','DateTY'], as_index=False)[
    ['IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']].max().groupby('IndustrySegmentName', as_index=False)[
    ['IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']].sum()

df_revPAR = pd.merge(df_brand, df_hotel, on='IndustrySegmentName')
© www.soinside.com 2019 - 2024. All rights reserved.