简体   繁体   English

如何使用numpy按季度分组并计算数组的平均值?

[英]How to group by quarter and calculate average from an array using numpy?

I'd like to utilize numpy to calculate the average of a set of values in each quarter from the below array:我想利用 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}]

I'd like the result to tell me the following:我希望结果告诉我以下内容:

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

Based on this stackoverflow question , I've tried the below:基于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

I think pandas works better in this case.我认为熊猫在这种情况下效果更好。 I will just use your simple example for illustration.我将仅使用您的简单示例进行说明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM