2017-04-04 108 views
1

假設我有一個形狀n X m(其中n是大數且m> = 1)的二維numpy數組。每列代表一個屬性。對於n的一個例子= 5,m = 3是提供如下:從2d numpy數組創建數據的歷史記錄?

[[1,2,3], 
[4,5,6], 
[7,8,9], 
[10,11,12], 
[13,14,15]] 

我想訓練與history_steps = P(1 < p < = n)的屬性的歷史我的模型。對於p = 2時,輸出I期望(形狀的(N-P + 1 X * M P))是

[[1,4,2,5,3,6], 
[4,7,5,8,6,9], 
[7,10,8,11,9,12], 
[10,13,11,14,12,15]] 

我試圖通過分離柱,然後串聯輸出,以實現此在大熊貓。

def buff(s, n): 
    return (pd.concat([s.shift(-i) for i in range(n)], axis=1).dropna().astype(float)) 

但是,對我而言,基於numpy的方法會更好。另外,我想避免分割和連接。

我該如何去做這件事?

+0

幾乎所有的熊貓功能都有,因爲大熊貓numpy的等效使用numpy的廣泛的引擎蓋下。你爲什麼不直接閱讀numpy文檔來搞清楚? (請注意,在大多數情況下,用'np.function'替換'pd.function'就行!) – Julien

+0

是的。我同意。然而,如何不分裂數據到列和做緩衝區 – GKS

+0

說實話,我沒有得到你想要做什麼,你想要的輸出背後的邏輯是什麼...... – Julien

回答

1

您可以使用dstack + reshape

a = np.array([[1,2,3], 
[4,5,6], 
[7,8,9], 
[10,11,12], 
[13,14,15]]) 

# use `dstack` to stack the two arrays(one with last row removed, the other with first 
# row removed), along the third axis, and then use reshape to flatten the second and third 
# dimensions 
np.dstack([a[:-1], a[1:]]).reshape(a.shape[0]-1, -1) 

#array([[ 1, 4, 2, 5, 3, 6], 
#  [ 4, 7, 5, 8, 6, 9], 
#  [ 7, 10, 8, 11, 9, 12], 
#  [10, 13, 11, 14, 12, 15]]) 

推廣到任意p,使用列表理解產生轉移陣列的列表,然後做stack+reshape

n, m = a.shape 
p = 3 
np.dstack([a[i:(n-p+i+1)] for i in range(p)]).reshape(n-p+1, -1) 

#array([[ 1, 4, 7, 2, 5, 8, 3, 6, 9], 
#  [ 4, 7, 10, 5, 8, 11, 6, 9, 12], 
#  [ 7, 10, 13, 8, 11, 14, 9, 12, 15]]) 
+0

p如何在這裏拍照?如果我想要p = 3,怎麼辦? – GKS

+0

更新了一種處理輪班的方法。 – Psidom

+0

現在看起來不錯。非常感謝! – GKS

2

這裏有一個與NumPy注重性能使用np.lib.stride_tricks.as_strided -

def strided_axis0(a, L = 2): 
    # INPUTS : 
    # a : Input array 
    # L : Length along rows to be cut to create per subarray 

    # Store shape and strides info 
    m,n = a.shape 
    s0,s1 = a.strides 
    nrows = m - L + 1 

    strided = np.lib.stride_tricks.as_strided 

    # Finally use strides to get the 3D array view and then reshape 
    return strided(a, shape=(nrows,n,L), strides=(s0,s1,s0)).reshape(nrows,-1) 

採樣運行 -

In [27]: a 
Out[27]: 
array([[ 1, 2, 3], 
     [ 4, 5, 6], 
     [ 7, 8, 9], 
     [10, 11, 12], 
     [13, 14, 15]]) 

In [28]: strided_axis0(a, L=2) 
Out[28]: 
array([[ 1, 4, 2, 5, 3, 6], 
     [ 4, 7, 5, 8, 6, 9], 
     [ 7, 10, 8, 11, 9, 12], 
     [10, 13, 11, 14, 12, 15]]) 
+0

這是新的。從來不知道這樣的東西存在於numpy中。 – GKS

+0

@GKS Yup,'np.lib.stride_tricks.as_strided'可能是NumPy中最深奧和最有效的東西。在過去的24小時內必須三次使用它來回答這裏的問題:) – Divakar