pandas 在给定半小时粒度的情况下,如何以小时粒度累积值?

w1jd8yoj  于 11个月前  发布在  其他
关注(0)|答案(4)|浏览(149)

我有以下pandas DataFrame df

DateTime              SENSOR   PROD
2019-04-01 00:00:00   0        0.0
2019-04-01 00:30:00   1        10.0
2019-04-01 01:00:00   1        5.0
2019-04-01 01:30:00   1        1.0
2019-04-01 02:00:00   1        12.0
2019-04-01 02:30:00   0        0.0

字符串
这些值是以半小时的粒度给出的。我应该以小时的粒度对PROD求和,得到以下结果。

DateTime              PROD
2019-04-01 00:00:00   10.0
2019-04-01 01:00:00   6.0
2019-04-01 02:00:00   12.0

4ioopgfo

4ioopgfo1#

你可以这样使用DataFrame.resample

df.resample('H').sum()

字符串
要使用resample,你需要确保你的索引是DatetimeIndex。我认为有几种方法可以做到这一点,但你可以尝试:

df.index = pd.DatetimeIndex(df.index)

cgvd09ve

cgvd09ve2#

可以使用resample

df.set_index('DateTime').resample('H').sum().drop('SENSOR', axis=1)

个字符

注意:如果您的DateTime列还不是datetime格式,请先执行以下操作:

df['DateTime'] = pd.to_datetime(df['DateTime'])

gkn4icbw

gkn4icbw3#

您需要使用pd.Grouper

df.set_index('DateTime').drop('SENSOR',1).groupby(pd.Grouper(freq='1h')).aggregate(np.sum)

字符串
输出量:

PROD
DateTime        
2019-04-01 00:00:00 10.0
2019-04-01 01:00:00 6.0
2019-04-01 02:00:00 12.0

daolsyd0

daolsyd04#

resample支持on选项来指定用于重采样而不是索引的列。因此,您不需要将_index设置为datetimeindex。只需在on中指定列名即可

df.resample('H', on='DateTime').PROD.sum()

Out[1948]:
DateTime
2019-04-01 00:00:00    10.0
2019-04-01 01:00:00     6.0
2019-04-01 02:00:00    12.0
Freq: H, Name: PROD, dtype: float64

字符串
另一种方法是使用groupbydf.DateTime向下转换为datetime64[h]

df.groupby(df.DateTime.astype('datetime64[h]')).PROD.sum()

Out[8]:
DateTime
2019-04-01 00:00:00    10.0
2019-04-01 01:00:00     6.0
2019-04-01 02:00:00    12.0
Name: PROD, dtype: float64

相关问题