python - 将一小时内的每个值分组为一个值,这是它的平均值
问题描述
我需要该小时内所有值的平均值,并且我需要在每天的所有这些时间里都这样做。
例如:
Date Col1
2016-01-01 07:00:00 1
2016-01-01 07:05:00 2
2016-01-01 07:17:00 3
2016-01-01 08:13:00 2
2016-01-01 08:55:00 10
.
.
.
.
.
.
.
.
2016-12-31 22:00:00 3
2016-12-31 22:05:00 3
2016-12-31 23:13:00 4
2016-12-31 23:33:00 5
2016-12-31 23:53:00 6
因此,我需要将该日期内该小时内的所有值组合为一个(意思是)。
预期输出:
Date Col1
2016-01-01 07:00:00 2 ##(2016-01-01 07:00:00, 07:05:00, 07:17:00) 3 values falls between the one hour range for that date i.e. 2016-01-01 07:00:00 - 2016-01-01 07:59:00, both inclusive.
2016-01-01 08:00:00 6
.
.
.
.
.
.
.
.
2016-12-31 22:00:00 3
2016-12-31 23:00:00 5
所以,如果我整年都这样做,那么最后总行数将是 365*24。
我尝试使用这个答案解决,但它不起作用。谁能帮我?
解决方案
resample
frompandas
应该适合你的情况
import pandas as pd
df = pd.DataFrame({
'Date':['2016-01-01 07:00:00','2016-01-01 07:05:00',
'2016-01-01 07:17:00' ,'2016-01-01 08:13:00',
'2016-01-01 08:55:00','2016-12-31 22:00:00',
'2016-12-31 22:05:00','2016-12-31 23:13:00',
'2016-12-31 23:33:00','2016-12-31 23:53:00'],
'Col1':[1, 2, 3, 2, 10, 3, 3, 4, 5, 6]
})
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') # Convert series to datetime type
df.set_index('Date', inplace=True) # Set Date column as index
# for every hour, take the mean for the remaining columns of the dataframe
# (in this case only for Col1, fill the NaN with 0 and reset the index)
df.resample('H').mean().fillna(0).reset_index()
df.head()
Date Col1
0 2016-01-01 07:00:00 2.0
1 2016-01-01 08:00:00 6.0
2 2016-01-01 09:00:00 0.0
3 2016-01-01 10:00:00 0.0
4 2016-01-01 11:00:00 0.0
推荐阅读
- swift - 错误:多个命令产生... x86_64.swiftmodule
- c# - 在更改时使用 DropDownList 传递多个数据字段
- r - 非线性回归故障排除
- python - Chrome headless 正在抛出 nosuchelements
- javascript - 当其他测试用例在另一个浏览器上运行时,我们可以从不同浏览器上的文件中执行一个“it”块吗?
- environment-variables - 不能在 GitLab 环境变量中使用 `$$` 字符
- jquery-ui - Vue2 和 jquery-ui datepicker :: minDate 没有动态更新
- python - 在 Python 中使用 PyMysql 连接 MariaDB 时出现问题
- node.js - 从 Babel 6 迁移到 7 导出默认值未定义
- sql-server - 在没有集成服务的情况下访问 SQL Server .dtsx 包