【问题标题】:How to group by quarter and calculate average from an array using numpy?如何按季度分组并使用numpy从数组中计算平均值?
【发布时间】:2016-07-22 12:18:33
【问题描述】:

我想利用 numpy 从下面的数组中计算每个季度的一组值的平均值:

Data = [{'date':'2015-01-01',value:5},{'date':'2015-02-01',value:6},{'date':'2015-03-01',value:7},{'date':'2015-04-01',value:8},{'date':'2015-05-01',value:9},{'date':'2015-06-01',value:10},{'date':'2015-07-01',value:11},{'date':'2015-08-01',value:12}]

我希望结果告诉我以下内容:

  • 对于 Q1-15,平均值为 6
  • 对于 Q2-15,平均值为 9
  • 对于 Q3-15,平均值为 11.5

基于this stackoverflow question,我尝试了以下方法:

np = Data #I'm not sure how to read in data into numpy from an array in my structure
np.resample('Q',how='mean') #I'm not sure if using 'Q' would group this by quarter

【问题讨论】:

  • 查看熊猫。您链接到的问题使用熊猫。

标签: python arrays numpy scipy


【解决方案1】:

我认为 pandas 在这种情况下效果更好。我将仅使用您的简单示例进行说明。

import pandas as pd # use recent version which has dt.quarter attr for time
import json
value = 'value' # to be able to read your Data string as json 
Data1 = json.dumps(Data) # need it to use read_json() method.
a = pd.read_json(Data1)
a[a['date'].dt.quarter == 1].mean() # 1st quarter
a[a['date'].dt.quarter == 2].mean() # 2nd quarter
a[a['date'].dt.quarter == 3].mean() # 3rd quarter

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多