如何用pandas计算从中午到中午的每日平均值?

How to calculate daily averages from noon to noon with pandas?

我对 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 的建议,但我真的不知道如何...

非常感谢您!感谢您的帮助!!

你可以减去你的时间和groupby:

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

对于较新版本的 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

您可以将时间偏移 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()