python Pandas : Aggregate data by hour and display it instead of the index

标签 python pandas date numpy

我想使用 pandas 按小时聚合一些数据并显示日期而不是索引。

我现在的代码如下:

import pandas as pd
import numpy as np

dates = pd.date_range('1/1/2011', periods=20, freq='25min')
data = pd.Series(np.random.randint(100, size=20), index=dates)

result = data.groupby(data.index.hour).sum().reset_index(name='Sum')

print(result)

它显示了以下内容:

   index  Sum
0      0  131
1      1  116
2      2  180
3      3   62
4      4   95
5      5  107
6      6   89
7      7  169

问题是我想显示与该小时关联的日期而不是索引。

我要实现的结果如下:

       index                Sum
0      2011-01-01 01:00:00  131
1      2011-01-01 02:00:00  116
2      2011-01-01 03:00:00  180
3      2011-01-01 04:00:00   62
4      2011-01-01 05:00:00   95
5      2011-01-01 06:00:00  107
6      2011-01-01 07:00:00   89
7      2011-01-01 08:00:00  169

有什么方法可以使用 pandas 轻松做到这一点?

最佳答案

data.groupby(data.index.strftime('%Y-%m-%d %H:00:00')).sum().reset_index(name='Sum')

关于 python Pandas : Aggregate data by hour and display it instead of the index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50632435/

相关文章:

python - 根据条件更改列的值

python-3.x - 查询多个数据框并绘制组直方图

Python根据条件追加到数据框列

mysql - 显示 mysql 查询中缺失日期的计数

javascript - 从 Momentjs 数组中添加阻止星期几的日期

javascript - 在 Internet Explorer 中无法将 UTC 日期转换为本地日期

python - 如何使用嵌套循环和函数 split() 创建列表字母计数器?

python - 以编程方式注释 python 脚本

python - 为Google Cloud Machine Learning项目存储图像的最佳方法?

python - 将列表转换为对角矩阵 DataFrame