简体   繁体   English

加快/改善循环的构建/性能

[英]Speed-up/Improve loop construction/performance

I am failrly new in Python. 我是Python的新手。 I wrote a script and I am surprised of the time it take to go through a particular loop compare to the rest of my code. 我编写了一个脚本,与我的其余代码相比,经历特定循环所花费的时间让我感到惊讶。

Can someone tell me what is inefficient in the code I wrote and maybe how to improve the speed ? 有人可以告诉我在我编写的代码中什么效率低下,或者如何提高速度吗?

Here is the loop in question : (BT_Histos and Histos_Last_Rebal are dataframes with dates in index and columns of floats. Portfolio and Portfolio_Last_Rebal are dataframes same index as the 2 previous one that i am filling through the loop. weights is just a list) 这里是有问题的循环:(BT_Histos和Histos_Last_Rebal是日期在浮点数的索引和列中的数据框。Portfolio和Portfolio_Last_Rebal是与我在循环中填充的前两个索引相同的数据框。权重只是一个列表)

Udl_Perf=BT_Histos/Histos_Last_Rebal-1

for i in range(1,len(BT_Histos.index)):
    """tricky because isin doesn't work with timestamp"""
    test_date=pd.Series(Portfolio.index[i-1])

    if test_date.isin(Rebalancing_Dates)[0]:
        Portfolio_Last_Rebal.loc[Portfolio_Last_Rebal.index[i],'PortSeries']=Portfolio.loc[Portfolio.index[i-1],'PortSeries']
    else:
        Portfolio_Last_Rebal.loc[Portfolio_Last_Rebal.index[i],'PortSeries']=Portfolio_Last_Rebal.loc[Portfolio_Last_Rebal.index[i-1],'PortSeries']

    Portfolio.loc[Portfolio.index[i],'PortSeries']=Portfolio_Last_Rebal.loc[Portfolio_Last_Rebal.index[i],'PortSeries']*(1+sum(Udl_Perf.iloc[i]*weights))

Thanks! 谢谢!

If you really want it to be fast then first implement it in while loop. 如果您真的希望它更快,那么请首先在while循环中实现它。

Second the length variable which you will use, define the type in advance using Mypy library , in this you need Python 3.5+ version installed. 其次要使用的length变量,使用Mypy库预先定义类型,在此您需要安装Python 3.5+版本。

Also if every iteration is unique then you can use multithreading using threading library . 同样,如果每个迭代都是唯一的,则可以使用线程库使用多线程 Get eg in this git repo 在此git仓库中获取例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM