2016-03-09 71 views
0

我目前正在開展的下面一行代碼:減法熊貓據幀之間相乘,numpy的陣列和浮

z = y-(X_array*HedgeRatio) 

與具有以下屬性變量:

Hedge Ratio = 0.489552919785 
Hedge Ratio type = <type 'numpy.float64'> 

y type = <class 'pandas.core.frame.DataFrame'> 
X_array type = <type 'numpy.ndarray'> 

y length = 1554 
X_array length = 1554 

但當它執行時,我得到以下長的錯誤信息:

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-161-6dd37e0445e9> in <module>() 
     1 #for i in get_symb_list(symbs): 
----> 2 MRAnalysis(symbs,'2010/01/01') 

<ipython-input-160-be6f6d5b64d0> in MRAnalysis(symbList, start_date) 
    63 
    64   #create new spread series by subtracting (X variable price multiplied by hedge ratio) from y price series 
---> 65   z = y-(X_array*HedgeRatio) 
    66 
    67   #plot spread series showing mean of series 

C:\Python27\lib\site-packages\pandas\core\ops.pyc in f(self, other, axis, level, fill_value) 
    838      # casted = self._constructor_sliced(other, 
    839      #         index=self.columns) 
--> 840      casted = pd.Series(other, index=self.columns) 
    841     return self._combine_series(casted, na_op, fill_value, 
    842            axis, level) 

C:\Python27\lib\site-packages\pandas\core\series.pyc in __init__(self, data, index, dtype, name, copy, fastpath) 
    216          raise_cast_failure=True) 
    217 
--> 218     data = SingleBlockManager(data, index, fastpath=True) 
    219 
    220   generic.NDFrame.__init__(self, data, fastpath=True) 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in __init__(self, block, axis, do_integrity_check, fastpath) 
    3381    block = make_block(block, 
    3382        placement=slice(0, len(axis)), 
-> 3383        ndim=1, fastpath=True) 
    3384 
    3385   self.blocks = [block] 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in make_block(values, placement, klass, ndim, dtype, fastpath) 
    2099 
    2100  return klass(values, ndim=ndim, fastpath=fastpath, 
-> 2101     placement=placement) 
    2102 
    2103 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in __init__(self, values, placement, ndim, fastpath) 
    75    raise ValueError('Wrong number of items passed %d,' 
    76        ' placement implies %d' % (
---> 77         len(self.values), len(self.mgr_locs))) 
    78 
    79  @property 

ValueError: Wrong number of items passed 1554, placement implies 1 

我是co因爲我認爲熊貓數據框架和numpy數組可以「交談」彼此,我會得到一個DataFrame或系列與計算概述進行逐行。

numpy數組的長度和代碼行中包含的DataFrame長度都相同。

是否有人可以指出我出錯的地方以及我誤解了什麼。

回答

1

其中一個陣列發生了轉置。

嘗試X_array.shapey.shape

y也是一個數據幀,它不清楚它包含多少個列。

你可以嘗試:

z = y.apply(lambda s: s - X_array * HedgeRatio) 

這將公式應用到各個系列數據框y的。

如果還是不行,請嘗試:

z = y.apply(lambda s: s - np.matrix(X_array).T * HedgeRatio) 
+0

對啊暗示千恩萬謝,以什麼打算錯了 - 我想我應該想到這一點時,該錯誤消息說,「1554個項目是通過」而不是1.我使用.reshape函數在我的腳本「X_array = X_array.reshape(len(X_array),1)」中對之前的數組進行了整形,現在它可以工作。謝謝你的幫助! – s666