【问题标题】:How do I get the sum of the revenue per month for the four id numbers with the highest total revenue using pandas?如何使用 pandas 获得总收入最高的四个 id 号码每月的收入总和?
【发布时间】:2020-09-21 09:18:57
【问题描述】:

我能够算出哪四个 source_id 的总收入最高,但我想将其进一步细分为按月收入。

最后,我想使用新的数据框来可视化前四个来源 ID 的月收入。

我能够使用 groupby 获得最高的总收入,但我不知道除此之外还能做什么。

rev_sum = joined_data.groupby("source_id")["revenue"].sum()
top_id = rev_sum.sort_values(ascending = False).head(4)
top_id
table name: joined_data

    date     source_id  cost    revenue
0   1/17/14     PA01    10.0    40.0
1   2/17/14     PA02    15.0    25.0
2   1/7/14      PA02    40.0    25.0
3   3/25/14     PA03    10.0    35.0
4   2/30/14     PA03    15.0    35.0
5   3/22/14     PA05    20.0    30.0
6   1/17/14     PA04    10.0    60.0
7   3/22/14     PA01    30.0    40.0
8   2/7/14      PA04    50.0    30.0
9   1/14/14     PA02    30.0    25.0
10  2/13/14     PA03    40.0    30.0
    ...         ...     ...     ...

在上面的示例数据中,“source_id”:PA01、PA02、PA03 和 PA04 的总收入最高。 最后,我想要一个新表,其每月明细如下所示:

source_id    month    month_rev
PA01         Jan      10.0
             Feb      30.0
             Mar      0.0
PA02         Jan      40.0
             Feb      15.0
             Mar      0.0
PA03         Jan      0.0
             Feb      55.0
             Mar      10.0
PA04         Jan      10.0
             Feb      50.0
             Mar      0.0

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    使用month 添加新列:

    df['month'] = [ar[0] for ar in df.date.str.split('/')]
    
    df['month'] = pd.to_datetime(df['month'],format='%m').dt.month_name()
    

    然后创建具有所需收入的新数据框:

    result = df.groupby(['source_id', 'month']).sum()[['cost']].reset_index()
    result = result.rename(columns={'cost':'month_revenue'})
    

    输出

    source_id   month   month_revenue
    0   PA01    January     10.0
    1   PA01    March       30.0
    2   PA02    February    15.0
    3   PA02    January     70.0
    4   PA03    February    55.0
    5   PA03    March       10.0
    6   PA04    February    50.0
    7   PA04    January     10.0
    8   PA05    March       20.0
    

    但是在空月中没有零。你真的需要它们吗?

    【讨论】:

      【解决方案2】:
      df['date'] = pd.to_datetime(df['date'])    
      df.groupby(df['date'].dt.strftime('%B'))['revenue'].sum().sort_values() 
      

      你可以试试这个,让我知道输出。我认为您正在使用 pandas 数据框。

      【讨论】:

      • 运行时出现错误:“AttributeError: Can only use .dt accessor with datetimelike values”
      • 添加了一个小调整来更改数据格式以实现更好的分组。
      猜你喜欢
      • 2022-12-15
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多