【问题标题】:How to get the index length of a condition in a pandas column vectorized如何在熊猫列矢量化中获取条件的索引长度
【发布时间】:2022-08-19 04:19:08
【问题描述】:

我有一个包含时间序列数据的数据集。当某个参数满足条件时,我想测量它的持续时间。
我可以循环遍历条件发生变化的所有位置,但这似乎效率低下。

进行矢量化的最佳方法是什么?

例子:

import numpy as np
import pandas as pd

np.random.seed(0)

# generate dataset:
df = pd.DataFrame({\'condition\': np.random.randint(0, 2, 24)}, 
                  index = pd.date_range(start=\'2020\', freq=\'M\', periods=24))

df

数据样本:

目标:
我的目标是在此示例中创建一个持续时间为 \'1\' 的子连续出现的列:

到目前为止我做了什么:

# find start and end of condition:
ends = df[df.condition.diff() < 0].index
start = df[df.condition.diff() > 0].index[:ends.size]

# loop through starts and determine length
for s, e in zip(start, ends):
    df.loc[e, \'duration\'] = e - s

# move 1 step back so it matches with last value position
df[\'duration\'] = df.duration.shift(-1)

在此示例中,这非常快,但循环使其在较大数据集时变慢。做这样的事情最快的方法是什么?

    标签: python pandas dataframe numpy indexing


    【解决方案1】:

    我设法对其进行矢量化的一种方法是使用.ffill() 创建一个临时列并向前填充其中的开始时间。然后从结束时间中减去开始时间:

    填写开始时间:

    df.loc[start, 'temp'] = start
    df.temp.ffill(inplace=True)
    
    

    输出:

    从结尾减去开始:

    df.loc[ends, 'duration'] = ends - df.loc[ends, 'temp']
    df['duration'] = df.duration.shift(-1)
    

    输出:

    这在具有 1e5 行的数据帧上要快 1000 倍:

    但我仍然想知道这是否可以进一步改进......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2021-12-28
      • 2015-05-07
      • 2021-09-15
      • 2020-10-02
      • 1970-01-01
      • 2022-11-16
      相关资源
      最近更新 更多