gpt4 book ai didi

python - 加速 Pandas 滚动引用另一个数据框

转载 作者:行者123 更新时间:2023-12-04 00:55:03 24 4
gpt4 key购买 nike

我想要一些有关如何优化以下 pandas 计算的反馈:

我们有一个固定索引集I 和一个lookback。此外,我们还有一个 pd.Series index 它的中位数回顾、index_MEDIAN 和大量的 pandas 数据帧列表。所有系列/数据帧都以 I 作为索引。每个数据框都有列 value。让 D 成为这样一个数据框..

对于 D 的每一行,我们在 index_MEDIAN 中取相应的值 m 并对回溯窗口中存在的所有值条目求和,受index系列中的运行值大于m的条件。换句话说,只要索引值大于回溯的中值,我们就会在 D 中对相应的值行求和。

为了更清楚地说明,这里是上述实现的草图

  def sumvals(x)

S = (D['value'].loc[x.index] >= self.index_median.loc[x.index[-1]])

return sum(S*(x-self.index_median.loc[x.index[-1]]))

D['value'].rolling(lookback).apply(sumvals)

数据帧列表非常庞大,我注意到这种计算数量的方法需要花费过多的时间。我怀疑这个问题与此实现大量使用 .loc 这一事实有关。因此

Is there another way to express this solution without having to reference an external Series so much?

无论哪种方式,我们都欢迎任何类型的优化建议。

编辑。这是一个包含相应计算的示例数据集。

lookback = 3
Index = pd.Series([1,-2,8,-10,3,4,5, 10, -20, 3])
Index_median = Index.rolling(lookback).median
Values = pd.Series([1,2,2,3,0,9,10, 8, 20, 9])

Values 的结果计算应该产生

0     NaN
1 NaN
2 2.0
3 13.0
4 0.0
5 6.0
6 11.0
7 12.0
8 23.0
9 28.0

例如第 5 行的值为 6。为什么?第 5 行中的 Index_median 值为 3。第 5 行中的 3-lookback 是序列 9、0、3。值 >= 是 3 和 9,因此这包括我们对第 5 行 3-3+9- 的总和3 = 6。类似地,对于最后一行,索引中位数是 3。值中的最后三行都大于 3,总和为 34 - 3*3 = 28。

最佳答案

从您的示例数据开始:

df = pd.DataFrame()
df['I'] = pd.Series([1,-2,8,-10,3,4,5, 10, -20, 3])
df['I_median'] = df['I'].rolling(lookback).median()
df['Values'] = pd.Series([1,2,2,3,0,9,10, 8, 20, 9])

现在为“值”列添加移位列

# add one column for every lookback    
for colno in range(lookback):

# shift the column by one and deduct the median
df['n'+ str(colno)] = df['Values'].shift(colno) - df['I_median']

# remove all negative numbers (where value is smaller than median)
df['n'+ str(colno)] = df['n'+ str(colno)].where(df['n'+ str(colno)]> 0, 0)

# sum up across the new columns
df['result'] = df[df.columns[-lookback:]].sum(axis=1)

df.result 包含你的结果并且等于

0     0.0
1 0.0
2 2.0
3 13.0
4 0.0
5 6.0
6 11.0
7 12.0
8 23.0
9 28.0
Name: result, dtype: float64

编辑:数据框中没有移动列

df['result'] = 0

for colno in range(lookback):
# shift the column by one and deduct the median
df['temp'] = df['Values'].shift(colno) - df['I_median']

# remove all negative numbers (where value is smaller than median)
df['temp'] = df['temp'].where(df['temp']> 0, 0)

# sum up across the new columns
df['result'] = df['result'] + df['temp']

性能

  • 数据框中有 100 万行
  • 1000 次回顾
lookback = 1000
df = pd.DataFrame()
df['I'] = pd.Series(np.random.randint(0, 10, size=1000000))
df['I_median'] = df['I'].rolling(lookback).median()
df['Values'] = pd.Series(np.random.randint(0, 10, size=1000000))

大约 14 秒后运行。

关于python - 加速 Pandas 滚动引用另一个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63130082/

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