【问题标题】:Speed-up/Improve loop construction/performance加速/改善循环结构/性能
【发布时间】:2019-01-29 15:42:10
【问题描述】:

我是 Python 的新手。我编写了一个脚本,与我的其余代码相比,我对通过特定循环所花费的时间感到惊讶。

谁能告诉我我写的代码效率低下的地方以及如何提高速度?

这是有问题的循环:(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))

谢谢!

【问题讨论】:

标签: python pandas performance loops


【解决方案1】:

如果你真的希望它很快,那么首先在while循环中实现它。

第二个你将使用的长度变量,使用Mypy library预先定义类型,这里你需要安装Python 3.5+版本。

此外,如果每次迭代都是唯一的,那么您可以使用 threading library 来使用多线程。 Get eg in this git repo

【讨论】:

    猜你喜欢
    • 2013-12-07
    • 1970-01-01
    • 2020-03-29
    • 2014-07-27
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2019-01-28
    • 2018-10-21
    相关资源
    最近更新 更多