【问题标题】:How do I lag a pandas series and create a new time lagged data frame?如何滞后 pandas 系列并创建新的时间滞后数据框?
【发布时间】:2018-12-02 23:53:59
【问题描述】:

我想从熊猫系列中创建一个时间滞后的熊猫数据框。

给定熊猫系列:

X = pd.Series(range(5))

预期输出:

    0   1   2
0   0   1   2.0
1   1   2   3.0
2   2   3   4.0
3   3   4   0.0

我已经实现了以下函数(带步长),但它在大型数据集上需要很长时间

def creat_time_lagged(x, shift, step):
    df = pd.DataFrame()
    for i in range(0, len(x), step):
        if i + shift - 1 < len(x):
            df['{}'.format(i)] = x.iloc[i : i + shift].values
        else:
            df['{}'.format(i)] = np.append(x.iloc[i:].values, np.zeros(shift - len(x.iloc[i:].values)))
            break
    return df

我该如何改进它?

【问题讨论】:

标签: python python-3.x pandas numpy


【解决方案1】:

方法#1

我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows 来获得滑动窗口。 More info on use of as_strided based view_as_windows.

from skimage.util.shape import view_as_windows

def create_time_lagged_viewaswindows(X, shift, step):  
    a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
    windows_ar = view_as_windows(a_ext,shift)[:len(X)-shift+step+1:step].T
    return pd.DataFrame(windows_ar)

一点解释: 基本思想是我们用零填充尾部,然后创建滑动窗口。要创建窗口,我们使用np.lib.stride_tricks.as_stridedskimage.util.view_as_windows

示例运行 -

In [166]: X = pd.Series(range(5))

In [167]: create_time_lagged_viewaswindows(X, shift=4, step=1)
Out[167]: 
   0  1  2
0  0  1  2
1  1  2  3
2  2  3  4
3  3  4  0

In [168]: create_time_lagged_viewaswindows(X, shift=4, step=2)
Out[168]: 
   0  1
0  0  2
1  1  3
2  2  4
3  3  0

方法 #2

我们还可以使用np.lib.stride_tricks.as_strided,这需要我们手动设置步幅并使用它来塑造 arg,但我们会避免使用早期方法的转置,这可能值得额外的性能提升。实现看起来像这样 -

def create_time_lagged_asstrided(X, shift, step):  
    a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
    strided = np.lib.stride_tricks.as_strided
    s = a_ext.strides[0]
    ncols = (len(X)-shift+2*step)//step
    windows_ar = strided(a_ext, shape=(shift,ncols), strides=(s,step*s))
    return pd.DataFrame(windows_ar)

大型阵列的计时 -

In [215]: X = pd.Series(range(10000))

# Original solution
In [216]: %timeit creat_time_lagged(X, shift=10, step=5)
1 loop, best of 3: 608 ms per loop

# Approach #1
In [217]: %timeit create_time_lagged_viewaswindows(X, shift=10, step=5)
10000 loops, best of 3: 146 µs per loop

# Approach #2
In [218]: %timeit create_time_lagged_asstrided(X, shift=10, step=5)
10000 loops, best of 3: 104 µs per loop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2016-12-05
    相关资源
    最近更新 更多