gpt4 book ai didi

optimization - 对 Pandas 系列进行迭代需要永远,但我想不出没有它的方法来解决这个问题。有没有更快的方法?

转载 作者:行者123 更新时间:2023-12-03 16:17:24 25 4
gpt4 key购买 nike

我有一个连续数字的 Pandas 系列,比如

import pandas as pd
D = pd.Series([2, 3, 4, 4, 5, 4, 3, 2, 3, 4, 5, 4, 3, 2, 1, 0],
index=pd.date_range(start='2015-01-02 12:00:00', periods=16, freq='s'))
D

2015-01-02 12:00:00 2
2015-01-02 12:00:01 3
2015-01-02 12:00:02 4
2015-01-02 12:00:03 4
2015-01-02 12:00:04 5
2015-01-02 12:00:05 4
2015-01-02 12:00:06 3
2015-01-02 12:00:07 2
2015-01-02 12:00:08 3
2015-01-02 12:00:09 4
2015-01-02 12:00:10 5
2015-01-02 12:00:11 4
2015-01-02 12:00:12 3
2015-01-02 12:00:13 2
2015-01-02 12:00:14 1
2015-01-02 12:00:15 0
Freq: S, dtype: int64

但是,我的特定数据集可能有一百万行。我有兴趣为每一行回答以下问题:

For each row i and a fixed positive number s, let S be the next index after i such that D[S]<=D[i]-s. What is the maximum value of D[j]-D[i] for j between i and S?



为了给这个问题提供一些直觉,该数据是一个股票指数的价格系列,我有兴趣知道,在每次以 s 价格设置止损订单之前,该系列达到的最高价格变化是多少.例如,当 s =2 时,我们正在寻找从现在到价格达到当前水平减去 2 之间的最大峰值。

我写了一个函数来为给定的行找到这个。首先,我取 D 的第一个差异,然后运行

def pmax(Ddiff, i, s):
values = Ddiff[i+1:].iteritems()
pmaxvalue = 0
pcurrentvalue=0
while pcurrentvalue>s:
try:
pcurrentvalue += values.next()[1]
except StopIteration:
return pmaxvalue
pmaxvalue = max(pmaxvalue, pcurrentvalue)
return pmaxvalue

和运行

peaks = []
for i in range(len(D)):
peaks.append(pmax(Ddiff, i, -2))

在玩具数据集上给出正确的输出。但是在我的实际数据集上需要很长时间。

我绞尽脑汁想想出一种矢量化的方法来做到这一点,但我不能。

谁能想出一种方法来更快地做到这一点?

最佳答案

对于您的玩具示例,您的解决方案非常快,但扩展性很差:

  • 10 行 --> 1.3ms
  • 100 行 --> 31.5ms
  • 1000 行 --> 2160 毫秒
  • 5000 行 --> 52500 毫秒

  • 我建议使用更基于 numpy 的方法,例如

    # create big dataframe
    n = 1000
    D = pd.Series(np.random.randint(0,6,n),
    index=pd.date_range(start='2015-01-02 12:00:00', periods=n, freq='s'))
    # compute differences
    Ddiff = D.diff()
    # compute cumulative sum of differences
    Dsum = Ddiff.cumsum()
    # set initial value from nan to 0
    Dsum[0] = 0

    def pmax2(Dsum, D, i, s):
    # find index S
    S = np.argmax(D.iloc[i+1:]<=D.iloc[i]-s)
    # get max amplitude
    l = np.max(Dsum.iloc[i:i+S+1]-Dsum.iloc[i])
    return l

    # compute for all individual entries
    peaks = []
    # use xrange instead of range
    for i in xrange(len(D)-1):
    peaks.append(pmax2(Dsum, D, i, 2))
    peaks.append(0)

    这就像
  • 10 行 --> 1.79ms
  • 100 行 --> 19.7ms
  • 1000 行 --> 200 毫秒
  • 5000 行 --> 1040 毫秒

  • 如果您需要更高的速度,您可以考虑并行化 for 循环。

    关于optimization - 对 Pandas 系列进行迭代需要永远,但我想不出没有它的方法来解决这个问题。有没有更快的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992246/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com