gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:13 25 4
gpt4 key购买 nike

我想利用 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}]

我希望结果告诉我以下信息:

  • 2015 年第 1 季度的平均值为 6
  • 15 年第 2 季度的平均值为 9
  • 2015 年第 3 季度的平均值为 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

最佳答案

我认为 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

关于python - 如何使用 numpy 按季度分组并计算数组的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36377550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com