python-3.x - 在 Pandas DataFrame 中满足条件时范围内的平均数据点
问题描述
我有一个非常大的数据集,有超过 400,000 行并且还在增长。我了解您不应该使用 itrows 来修改熊猫数据框。但是,我对在这种情况下应该做什么有点迷茫,因为我不确定我是否可以使用 .loc() 或一些滚动过滤器以我需要的方式修改数据框。我试图弄清楚是否可以在满足条件时获取数据框并平均范围。例如:
健康)状况 | 温度。 | 压力 |
---|---|---|
1 | 8 | 20 |
1 | 7 | 23 |
1 | 8 | 22 |
1 | 9 | 21 |
0 | 4 | 33 |
0 | 3 | 35 |
1 | 9 | 21 |
1 | 11 | 20 |
1 | 10 | 22 |
当条件为 == 1 时,输出的数据帧将如下所示:
健康)状况 | 平均 温度。 | 平均 压力 |
---|---|---|
1 | 8 | 21.5 |
1 | 10 | 21 |
有没有人尝试过类似的事情可以让我走上正确的道路?我正在考虑使用这样的东西:
df = pd.csv_read(csv_file)
for index, row in df.iterrows():
if row['condition'] == 1:
#start index = first value that equals 1
else: #end index & calculate rolling average of range
len = end - start
new_df = df.rolling(len).mean()
我知道我的代码不是很好,我也知道我可以强制它执行与上面所示类似的操作,但正如我所说,它有很多行并且还在继续增长,所以我需要提高效率。
解决方案
尝试:
result = df.groupby((df.Condition != df.Condition.shift()).cumsum()).apply(
lambda x: x.rolling(len(x)).mean().dropna()).reset_index(drop=True)
print(result.loc[result.Condition.eq(1)]) # filter by required condition
输出:
Condition Temp. Pressure
0 1.0 8.0 21.5
2 1.0 10.0 21.0
推荐阅读
- html - 如何使用 CSS FlexBox 创建复杂的页面布局
- python - Python:并非所有参数都在字符串格式期间转换
- amazon-web-services - AWS API Gateway - Lambda - 内部服务器错误
- java - 在多线程环境中使用 for 循环避免 ConcurrentModificationException
- postgresql - 将 Ansible 返回值映射到第二个任务
- swift - Vapor:如何协调多个请求,直到完成一个中心请求
- javascript - 每次点击创建单独和独特的工具提示
- javascript - 使用 for 循环创建变量
- python - MongoEngine Python AttributeError
- swift - 使用 SwiftUI 将 TextField 添加到 NavigationBar