首页 > 解决方案 > 优化数据帧的迭代

问题描述

我的数据框看起来像这样:

            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 个与设备充电期相对应的样本子集:

注意:充电期并不总是像样品 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'),两者都有很大帮助。

还有其他我可以做的优化吗?,比如使用数据框应用函数(它似乎作为每一行的循环,但我不知道如何在这种情况下使用它,或者是否值得使用她),或者我可以使用的任何其他优化在我的解决方案中

标签: pythonpandas

解决方案


首先创建一个列,使用它唯一地分割您的数据框cumsum

df['group'] = (df.battery_state == 'Full').cumsum().shift(1).fillna(0)

现在您可以遍历组而不是遍历行

for index, frame in df.groupby('group'):
    subsetFunction(frame)

推荐阅读