【问题标题】:Get the average year (mean of days over multiple years) in Pandas获取 Pandas 的平均年份(多年的平均天数)
【发布时间】:2015-04-03 00:01:41
【问题描述】:

我是 Pandas 时间序列和数据框的新手,很难完成这个简单的任务。 从 2004 年 1 月 1 日到 2008 年 12 月 31 日,我每天都有一个数据集“数据”(一维 float32-Numpy 数组)。日期存储为日期时间对象“日期”的列表。 基本上,我想计算一个完整的“标准年”——所有年份(1-365)中每一天的平均值。 我从这个类似的 (?) 问题 (Getting the average of a certain hour on weekdays over several years in a pandas dataframe) 开始,但无法达到预期的结果 - 365“平均”天的时间序列,例如1 月 1 日和 1 月 2 日所有四个的平均值...

一个小示例脚本:

import numpy as np
import pandas as pd
import datetime

startdate = datetime.datetime(2004, 1, 1)
enddate = datetime.datetime(2008, 1, 1)
days = (enddate + datetime.timedelta(days=1) - startdate).days
data = np.random.random(days)
dates = [startdate + datetime.timedelta(days=x) for x in range(0, days)]

ts = pd.Series(data, dates)
test = ts.groupby(lambda x: (x.year, x.day)).mean()

【问题讨论】:

    标签: python datetime numpy pandas time-series


    【解决方案1】:

    按月日分组,而不是年日分组:

    test = ts.groupby([ts.index.month, ts.index.day]).mean()
    

    产量

    1  1     0.499264
       2     0.449357
       3     0.498883
    ...
    12  17    0.408180
        18    0.317682
        19    0.467238
    ...    
        29    0.413721
        30    0.399180
        31    0.828423
    Length: 366, dtype: float64
    

    【讨论】:

    • 谢谢,为此搜索了很长时间:)
    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2021-01-30
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多