对于任何给定的日期,我都试图找到前一个close
值,该值是当前close
值的1.2倍。我做了一个循环,将检查每一行。然而,这是没有效率的。运行时间为45秒。如何使我的代码更高效地处理比这大得多的数据集
数据集-TSLA 或TSLA Daily 5Y Stock Yahoo
df = pd.read_csv(os.getcwd()+"\\TSLA.csv")
# Slicing the dataset
df2 = df[['Date', 'Close']]
irange = np.arange(1, len(df))
for i in irange:
# Dicing first i rows
df3 = df2.head(i)
# Set the target close value that is 1.2x the current close value
targetValue = 1.2 * df3['Close'].tail(1).values[0]
# Check the last 200 days
df4 = df3.tail(200)
df4.set_index('Date', inplace=True)
# Save all the target values in a list
req = df4[df4['Close'] > targetValue]
try:
lent = (req.index.tolist()[-1])
except:
lent = str(9999999)
# Save the last value to the main dataframe
df.at[i,'last_time'] = lent
df.tail(20)
您正在执行O(N^3)和一些不必要的数据拷贝。试试这个O(NlogN)方式
相关问题 更多 >
编程相关推荐