【问题标题】:Python: Grouping by date and finding the average of a column inside a dataframePython:按日期分组并查找数据框中列的平均值
【发布时间】:2017-11-12 00:31:39
【问题描述】:

我有一个包含 3 列的数据框。 时间代表各个月份的每一天。我要做的是每天获取“计数”值并每月平均,并为每个国家/地区执行此操作。输出必须是数据框的形式。

当前数据:

    Time    Country Count
 2017-01-01    us   7827
 2017-01-02    us   7748
 2017-01-03    us   7653
 ..
 ..
 2017-01-30    us   5432
 2017-01-31    us   2942
 2017-01-01    us   5829
 2017-01-02    ca   9843
 2017-01-03    ca   7845
 ..
 ..
 2017-01-30    ca   8654
 2017-01-31    ca   8534

Desire output(虚拟数据,数字不代表上面的DF):

    Time       Country   Monthly Average
 Jan 2017      us          6873
 Feb 2017      us          8875
 ..
 .. 
 Nov 2017      us          9614
 Dec 2017      us          2475
 Jan 2017      ca          1878
 Feb 2017      ca          4775
 ..
 .. 
 Nov 2017      ca          7643
 Dec 2017      ca          9441

【问题讨论】:

  • You Count 列令人困惑。它是原始数据框的列还是 groupby 的结果列?另外,我不确定为什么需要计数和平均值。可以直接按平均值聚合。
  • 它应该来自原始数据框。基本上将每个月的所有值相加,然后取平均值。

标签: python pandas dataframe grouping


【解决方案1】:

我会这样组织它:

df.groupby(
    [df.Time.dt.strftime('%b %Y'), 'Country']
)['Count'].mean().reset_index(name='Monthly Average')

       Time Country  Monthly Average
0  Feb 2017      ca             88.0
1  Feb 2017      us            105.0
2  Jan 2017      ca             85.0
3  Jan 2017      us             24.6
4  Mar 2017      ca             86.0
5  Mar 2017      us             54.0

如果您的 'Time' 列还不是日期时间列,我会这样做:

df.groupby(
    [pd.to_datetime(df.Time).dt.strftime('%b %Y'), 'Country']
)['Count'].mean().reset_index(name='Monthly Average')

       Time Country  Monthly Average
0  Feb 2017      ca             88.0
1  Feb 2017      us            105.0
2  Jan 2017      ca             85.0
3  Jan 2017      us             24.6
4  Mar 2017      ca             86.0
5  Mar 2017      us             54.0

【讨论】:

  • 由于某种原因,当我使用您的第二个实现时,我不断收到以下错误:'function' object has no attribute 'mean' 有什么想法吗?
  • 您使用的是小写count,这是一个函数。我会更新帖子
【解决方案2】:

使用pandas dt strftime 创建您想要的月-年列 + groupby + mean。使用了这个数据框:

Dated     country   num 
2017-01-01  us     12   
2017-01-02  us     12   
2017-02-02  us     134  
2017-02-03  us     76   
2017-03-30  us     54   
2017-01-31  us     29   
2017-01-01  us     58   
2017-01-02  us     12   
2017-02-02  ca     98   
2017-02-03  ca     78   
2017-03-30  ca     86   
2017-01-31  ca     85   

然后创建一个 Month-Year 列:

a['MonthYear']= a.Dated.dt.strftime('%b %Y')

然后,删除 Date 列并按平均值聚合:

a.drop('Dated', axis=1).groupby(['MonthYear','country']).mean().rename(columns={'num':'Averaged'}).reset_index()

MonthYear      country  Averaged
Feb 2017    ca      88.0
Feb 2017    us      105.0
Jan 2017    ca      85.0
Jan 2017    us      24.6
Mar 2017        ca      86.0
Mar 2017        us      54.0

我保留了 Dated 列以防万一。

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 2021-09-15
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多