python - 优化数据帧的迭代
问题描述
我的数据框看起来像这样:
timestamp battery_state battery_level
0 2017-10-08 13:42:02 Charging 0.94
1 2017-10-08 13:45:43 Charging 0.95
2 2017-10-08 13:49:08 Charging 0.96
3 2017-10-08 13:54:07 Charging 0.97
4 2017-10-08 13:57:26 Charging 0.98
5 2017-10-08 14:01:35 Charging 0.99
6 2017-10-08 14:03:03 Full 1.00
7 2017-10-08 14:17:19 Charging 0.98
8 2017-10-08 14:26:05 Charging 0.97
9 2017-10-08 14:46:10 Charging 0.98
10 2017-10-08 14:47:47 Full 1.00
11 2017-10-08 16:36:24 Charging 0.91
12 2017-10-08 16:40:32 Charging 0.92
13 2017-10-08 16:47:58 Charging 0.93
14 2017-10-08 16:51:51 Charging 0.94
15 2017-10-08 16:55:26 Charging 0.95
正如你们在这个数据框中看到的那样,我有 3 个与设备充电期相对应的样本子集:
- 样品 0 到 6
- 样品 7 到 10
- 样品 11 至 15
注意:充电期并不总是像样品 11 到 15 那样处于满状态
目标是将这 3 个时期变成一个变量,并在它们建立时对其进行处理。
为此,我编写了以下代码:
previous_index = 0 #stores the initial index of each period
for index in islice(device_charge_samples.index, 1, None): #use islice because the first row does not have privious sample to compare
#creates a period by comparing each line two by two
if device_charge_samples.get_value(index, 'battery_level') < device_charge_samples.get_value(index - 1, 'battery_level'):
subset = device_charge_samples[previous_index:index].reset_index(drop=True)
#Process subset function here
previous_index = index
#last period case
if index == len(device_charge_samples) - 1:
subset = device_charge_samples[previous_index:index + 1].reset_index(drop=True)
#Process subset function here
我已经在 for 循环中将device_charge_samples.iteraterows()替换为device_charge_samples.index并且我将device_charge_samples.loc[index, 'battery_level]替换为device_charge_samples.get_value(index, 'battery_level'),两者都有很大帮助。
还有其他我可以做的优化吗?,比如使用数据框应用函数(它似乎作为每一行的循环,但我不知道如何在这种情况下使用它,或者是否值得使用她),或者我可以使用的任何其他优化在我的解决方案中
解决方案
首先创建一个列,使用它唯一地分割您的数据框cumsum
df['group'] = (df.battery_state == 'Full').cumsum().shift(1).fillna(0)
现在您可以遍历组而不是遍历行
for index, frame in df.groupby('group'):
subsetFunction(frame)
推荐阅读
- ios - SwiftUI:尝试更改位置授权时出错
- arrays - 谷歌表格 - 我如何按团队返回参与者分数,按分数排序?
- date - 有没有办法使用 JavaScript 将预定义的日期传递到 Google 表单
- javascript - Javascript 和返回函数
- javascript - 从 ReactJs 中的嵌套 axios 调用返回值的问题
- javascript - 为什么 JavaScript 原始变量是不可变的?
- postgresql - Postgres 使用 seq 扫描而不是仅索引扫描
- python - 赋值之前引用的局部变量,但不是
- node.js - Jest Typescript with ES Module in node_modules 错误 - 必须使用导入来加载 ES 模块:
- docker - 我可以在 Docker Compose 中使用主机名构建插值字符串吗?