【问题标题】:How to calculate daily averages from noon to noon with pandas?如何用熊猫计算从中午到中午的每日平均值?
【发布时间】:2020-03-10 15:21:32
【问题描述】:

我对 python 和 pandas 还很陌生,所以对于以后的任何误解,我深表歉意。

我有一个带有每小时值的 pandas DataFrame,看起来像这样:

2014-04-01 09:00:00 52.9    41.1    36.3

2014-04-01 10:00:00 56.4    41.6    70.8

2014-04-01 11:00:00 53.3    41.2    49.6

2014-04-01 12:00:00 50.4    39.5    36.6

2014-04-01 13:00:00 51.1    39.2    33.3

2016-11-30 16:00:00 16.0    13.5    36.6

2016-11-30 17:00:00 19.6    17.4    44.3

现在我需要计算从 2014-04-01 12:00 到 2014-04-02 11:00 开始的每列的 24 小时平均值 所以我想要从中午到中午的每日平均值。

不幸的是,我不知道该怎么做。我已经阅读了一些使用 groupby 的建议,但我真的不知道如何...

提前非常感谢您!任何帮助表示赞赏!

【问题讨论】:

    标签: python pandas datetime mean


    【解决方案1】:

    对于较新版本的 pandas (>= 1.1.0),请使用 offset 参数:

    df.resample('24H', offset='12H').mean()
    

    base 参数。

    一天是 24 小时,因此以 12 为基数将从中午开始分组。 Resample 为您提供介于两者之间的所有时间,因此如果您不需要完整的基础,您可以.dropna(how='all')。 (我假设你有一个 DatetimeIndex,如果没有,你可以使用 resample 的 on 参数来指定你的日期时间列。)

    df.resample('24H', base=12).mean()
    #df.groupby(pd.Grouper(level=0, base=12, freq='24H')).mean() # Equivalent 
    
                             1      2          3
    0                                           
    2014-03-31 12:00:00  54.20  41.30  52.233333
    2014-04-01 12:00:00  50.75  39.35  34.950000
    2014-04-02 12:00:00    NaN    NaN        NaN
    2014-04-03 12:00:00    NaN    NaN        NaN
    2014-04-04 12:00:00    NaN    NaN        NaN
    ...                    ...    ...        ...
    2016-11-26 12:00:00    NaN    NaN        NaN
    2016-11-27 12:00:00    NaN    NaN        NaN
    2016-11-28 12:00:00    NaN    NaN        NaN
    2016-11-29 12:00:00    NaN    NaN        NaN
    2016-11-30 12:00:00  17.80  15.45  40.450000
    

    【讨论】:

    • 绝对是未充分利用的论点之一。可能是因为自己进行操作通常更简单/更明显:D
    • 非常感谢!!完美运行!
    【解决方案2】:

    你可以减去你的时间和分组:

    df.groupby((df.index - pd.to_timedelta('12:00:00')).normalize()).mean()
    

    【讨论】:

      【解决方案3】:

      您可以将小时数调整 12 小时,然后按天重新采样。

      from io import StringIO
      import pandas as pd
      
      data = """
      2014-04-01 09:00:00,52.9,41.1,36.3
      2014-04-01 10:00:00,56.4,41.6,70.8
      2014-04-01 11:00:00,53.3,41.2,49.6
      2014-04-01 12:00:00,50.4,39.5,36.6
      2014-04-01 13:00:00,51.1,39.2,33.3
      2016-11-30 16:00:00,16.0,13.5,36.6
      2016-11-30 17:00:00,19.6,17.4,44.3
      """
      
      df = pd.read_csv(StringIO(data), sep=',', header=None, index_col=0)
      
      df.index = pd.to_datetime(df.index)
      # shift by 12 hours
      df.index = df.index - pd.Timedelta(hours=12)
      # resample and drop na rows
      df.resample('D').mean().dropna()
      

      【讨论】:

        猜你喜欢
        • 2022-11-21
        • 2020-08-09
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2018-10-26
        • 2019-11-24
        • 2023-01-31
        • 2021-02-27
        相关资源
        最近更新 更多