Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何加速数据帧行上的迭代_Python 3.x_Pandas - Fatal编程技术网

Python 3.x 如何加速数据帧行上的迭代

Python 3.x 如何加速数据帧行上的迭代,python-3.x,pandas,Python 3.x,Pandas,尝试ItErrorws()时速度非常慢,在别处读取zip会更好,但仍然非常慢 我试图搜索一个数据帧的行,生成一些统计数据来填充两个新的数据帧 有没有加快数据帧行搜索速度的建议 代码片段: for index,date,stocknum in zip(stockpicks.index.values,stockpicks.date.values,stockpicks.stocknum.values): stock=readStockPrice(stocknum) i

尝试ItErrorws()时速度非常慢,在别处读取zip会更好,但仍然非常慢

我试图搜索一个数据帧的行,生成一些统计数据来填充两个新的数据帧

有没有加快数据帧行搜索速度的建议

代码片段:

for index,date,stocknum in zip(stockpicks.index.values,stockpicks.date.values,stockpicks.stocknum.values):

        stock=readStockPrice(stocknum)
        if stock.empty:
            return print("error - empty frame")
        stock=stock.ix[trading_days]
        stockprice=stock.Close.values
        p0_date=trading_days.get_loc(date)


        p0=stockprice[p0_date]
        stock_pct_change={('d'+str(d)):stockprice[p0_date+d]/p0*100.0 if (p0_date+d)< len(trading_days) else np.nan for d in days }

        b0=hsi[p0_date]
        benchmark_pct_change={('d'+str(d)):hsi[p0_date+d]/b0*100.0 if (p0_date+d)< len(trading_days) else np.nan for d in days }

        for d in days:
            stock_analysis.loc[index,'d'+str(d)]=stock_pct_change['d'+str(d)]
            benchmark_analysis.loc[index,'d'+str(d)]=benchmark_pct_change['d'+str(d)]
对于zip中的索引、日期、stocknum(stockpicks.index.values、stockpicks.date.values、stockpicks.stocknum.values):
stock=readStockPrice(stocknum)
如果库存为空:
返回打印(“错误-空帧”)
股票=股票.ix[交易日]
股票价格=stock.Close.values
p0\u日期=交易日。获取loc(日期)
p0=股票价格[p0\U日期]
股票价格变化={('d'+str(d)):股票价格[p0_日期+d]/p0*100.0如果(p0_日期+d)
您出现的问题可以完全矢量化。像您这样的迭代和索引是最慢的方法

In [6]: df = DataFrame(np.random.randint(-5,5,size=20).reshape(5,4),columns=list('abcd'),index=date_range('20130101',periods=5))+50.0

In [7]: df.pct_change()
Out[7]: 
                   a         b         c         d
2013-01-01       NaN       NaN       NaN       NaN
2013-01-02  0.108696  0.108696  0.102041  0.086957
2013-01-03 -0.058824 -0.039216 -0.074074 -0.060000
2013-01-04  0.104167  0.081633 -0.020000  0.000000
2013-01-05 -0.075472 -0.113208  0.061224 -0.021277

[5 rows x 4 columns]

杰夫,谢谢你的回答。。然而,你可能已经错过了我问题的焦点。我的代码不打算计算股票报价矩阵的pct变化,它首先必须通过stockpicks df搜索股票和感兴趣的日期,从存储的csv中检索相关股票报价,并计算pct_变化(以天为单位)[1,2,5,10,20,30…250]。因此,我必须迭代股票选择行(搜索)并将其索引到关注的股票价格中。