2017-07-14 67 views
2

給定以下具有60個元素的熊貓數據框。重新調整價格表從較長的長度到較小的長度

import pandas as pd 
data = [60,62.75,73.28,75.77,70.28 
    ,67.85,74.58,72.91,68.33,78.59 
    ,75.58,78.93,74.61,85.3,84.63 
    ,84.61,87.76,95.02,98.83,92.44 
    ,84.8,89.51,90.25,93.82,86.64 
    ,77.84,76.06,77.75,72.13,80.2 
    ,79.05,76.11,80.28,76.38,73.3 
    ,72.28,77,69.28,71.31,79.25 
    ,75.11,73.16,78.91,84.78,85.17 
    ,91.53,94.85,87.79,97.92,92.88 
    ,91.92,88.32,81.49,88.67,91.46 
    ,91.71,82.17,93.05,103.98,105] 

data_pd = pd.DataFrame(data, columns=["price"]) 

是否有一個公式,以便爲每個窗口開始從索引0到索引i+1大於20組的元素,該數據被重新縮​​放至20層的元件以這樣的方式重新調整此?

這裏是一個循環,正在創建與重新縮放數據的窗口,我只是不知道任何方式來做這個問題在手邊重新縮放本身。有關如何做到這一點的任何建議?

miniLenght = 20 
rescaledData = [] 
for i in range(len(data_pd)): 
    if(i >= miniLenght): 
     dataForScaling = data_pd[0:i] 
     scaledDataToMinLenght = dataForScaling #do the scaling here so that the length of the rescaled data is always equal to miniLenght 
     rescaledData.append(scaledDataToMinLenght) 

基本上後的重新縮放rescaledData應該有40陣列,每個陣列爲20倍的價格的長度。

+0

你做什麼重新調整? –

+0

這個問題真的來自科學論文,我試圖重現結果,但我很難做到重新縮放。 [Here](http://content.iospress.com/articles/algorithmic-finance/af059#eq3)是我發現的一個公式,我只是不知道如何在這裏應用 – RaduS

+0

請看[ df.rolling'](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html)。可能有些用處。用於窗口滾動的 –

回答

3

從閱讀文章看來,您似乎將列表重新調整爲20個索引,然後在20個索引處插入數據。

我們會像他們那樣製作索引(range(0, len(large), step = len(large)/miniLenght)),然後使用numpys interp - 有一百萬種插值數據的方法。 np.interp使用線性插值,因此如果您要求例如索引1.5,則可以得到點1和2的均值,依此類推。

所以,這裏是你的代碼的快速修改做(注意,我們也許可以完全矢量化這個使用「滾動」):

import numpy as np 
miniLenght = 20 
rescaledData = [] 

for i in range(len(data_pd)): 
    if(i >= miniLenght): 
     dataForScaling = data_pd['price'][0:i] 
     #figure out how many 'steps' we have 
     steps = len(dataForScaling) 
     #make indices where the data needs to be sliced to get 20 points 
     indices = np.arange(0,steps, step = steps/miniLenght) 
     #use np.interp at those points, with the original values as given 
     rescaledData.append(np.interp(indices, np.arange(steps), dataForScaling)) 

,並預期輸出:

[array([ 60. , 62.75, 73.28, 75.77, 70.28, 67.85, 74.58, 72.91, 
     68.33, 78.59, 75.58, 78.93, 74.61, 85.3 , 84.63, 84.61, 
     87.76, 95.02, 98.83, 92.44]), 
array([ 60. , 63.2765, 73.529 , 74.9465, 69.794 , 69.5325, 
     74.079 , 71.307 , 72.434 , 77.2355, 77.255 , 76.554 , 
     81.024 , 84.8645, 84.616 , 86.9725, 93.568 , 98.2585, 
     93.079 , 85.182 ]),..... 
+0

謝謝@jeremycg的答案。就是這樣:)我會在15小時內給予這個答案,當它允許我;) – RaduS

+0

謝謝!很高興它的工作 – jeremycg