通过数组执行嵌套循环的更多"Pythonian"方法?



下面的代码试图解决以下任务:"找到任何 5 天滚动窗口内的最大价格变化,超过 1000 天"。

"任何 5 天滚动窗口",我的意思不仅仅是"t_i + 5",而是"t_i + j",其中"i"从 1 到 1000 变化,"j"从 1 到 5 变化。

我尝试使用 Numpy 本机函数,但我最终仍然使用"for 循环"进行内部迭代。代码如下:

prices = npr.random([1000,1])*1000
max_array = np.zeros([(prices.size-5),1])
for index, elem in np.ndenumerate(prices[:-5,:]):
local_max = 0.0
for i in range(1,6,1):
price_return = prices[(index[0] + i),0] / elem
local_max = max(local_max, price_return)
max_array[index[0]] = local_max
global_max = np.amax(max_array)

我可以以某种方式消除内部 for 循环并改用 Numpy 矢量化(以某种方式(吗?

另外,我不太喜欢使用"index[0]"从元组对象中提取当前循环的实际索引,该元组对象通过调用返回到变量"index"中:

for index, elem in np.ndenumerate(prices[:-5,:]):

这也能改善吗?

使用熊猫滚动窗口进行最小和最大

允许在没有 for 循环的情况下进行计算

灵感来自 NumPy 数组中滑动窗口中的 Max

import pandas as pd
import numpy as np
# Generate Data
prices = np.random.random([1000,1])*1000
prices = prices.flatten()
# Pandas rolling window (max in 5 day period)
# Convert series back to numpy array
maxs = pd.Series(prices).rolling(5).max().dropna().to_numpy()
# Pandas rolling window (min in 5 day period)
# Convert series back to numpy array
mins = pd.Series(prices).rolling(5).min().dropna().to_numpy()
# Numpy subtraction to find max and min differnce
delta = maxs - mins

结果(显示前 10 个元素(

print('prices: ', prices[:10])
print('maxs: ', maxs[:10])
print('mins: ', mins[:10])
print('max-change: ', delta[:10])

输出(前 10 个元素(

prices:  [416.67356904 244.29395291 325.50608035 102.67426207 794.36067353
318.22836941 113.48811096 898.87130071 303.06297351 285.80963998]
maxs:  [794.36067353 794.36067353 794.36067353 898.87130071 898.87130071
898.87130071 898.87130071 898.87130071 828.87148828 828.87148828]
mins:  [102.67426207 102.67426207 102.67426207 102.67426207 113.48811096
113.48811096 113.48811096 285.80963998 285.80963998 106.4036413 ]
max-change:  [691.68641146 691.68641146 691.68641146 796.19703863 785.38318975
785.38318975 785.38318975 613.06166073 543.06184831 722.46784698]

最新更新