【问题标题】:Get maximum rows from all subgroups with groupby method (Python)使用 groupby 方法从所有子组中获取最大行数 (Python)
【发布时间】:2022-12-03 07:00:56
【问题描述】:

我有这个数据框,里面有 3 列“地区”、“州或省”、“销售额” 我已经按地区和州或省分组,并希望获得销售价值。但是我想从每个区域获得最大状态!我怎样才能得到那个?

sales_by_state = df_n.groupby(['Region', 'State or Province'])['Sales'].sum()
sales_by_state = sales_by_state.to_frame()
sales_by_state

【问题讨论】:

    标签: python pandas dataframe group-by max


    【解决方案1】:

    要获得每个区域的最大销售额,您可以使用'idxmax()'groupby 对象上的函数。这将返回每个组的最大值的索引,然后您可以使用它来索引原始数据框以获取相应的行。

    这是一个例子:

    # Get the maximum sales for each region
    max_sales = sales_by_state.groupby(level=0)['Sales'].idxmax()
    
    # Use the index of the maximum sales to index into the original data frame
    max_sales_by_state = df_n.loc[max_sales]
    

    这将返回一个新的数据框,其中包含原始数据框中与每个区域的最大销售额相对应的行。然后,您可以访问中的值“州或省”列以获得每个区域的最大状态。

    或者,您可以使用'申请()'groupby 对象上的方法将自定义函数应用于每个组。此函数可以返回该组销售额最大的州,然后您可以使用它在数据框中创建一个新列,其中包含每个地区的最大州。

    这是一个例子:

    # Define a custom function that returns the state with the maximum sales for a group
    def get_max_state(group):
      # Index into the group to get the state with the maximum sales
      return group.loc[group['Sales'].idxmax()]['State or Province']
    
    # Apply the custom function to each group and create a new column with the results
    sales_by_state['Max State'] = sales_by_state.groupby(level=0).apply(get_max_state)
    

    这将添加一个新列到'sales_by_state'包含每个区域的最大状态的数据框。

    【讨论】:

      猜你喜欢
      • 2018-12-31
      相关资源
      最近更新 更多