我有一個執行以下操作的函式:
- Takes 使用串列作為輸入
- 計算串列的總和
- 將輸出(總和)附加到輸入串列
- 再次運行自身(這次使用 N 1 個資料的串列)。
我想為一個 numpy 陣列的輸入做這個確切的事情,但我沒有得到一個完整的解決方案。
這是我目前擁有的:
data = [15.5, 19.2, 27.8, 44.6, 71.0, 54.1, 60.2]
def AppendOutput(data, steps):
for i in range(steps):
s = sum(data)
emp.append(s)
data.append(emp)
return data
s = AppendOutput(data, 3)
這會輸出以下內容,這就是我想要的:
[15.5, 19.2, 27.8, 44.6, 71.0, 54.1, 60.2, 292.4, 584.8, 1169.6]
我當前的問題是我正在嘗試為一個 numpy 陣列的輸入完成同樣的事情。
data_array = np.array([data])
def AppendOutputNP(data, steps):
for j in range(steps):
temp = np.sum(data_array).reshape((-1,1))
new = np.append(data_array, temp, axis=1)
return new
AppendOutputNP(data_array, 3)
與原始功能相比,我得到了部分解決方案;這次只添加了一個元素而不是三個:
array([[ 15.5, 19.2, 27.8, 44.6, 71. , 54.1, 60.2, 292.4]])
誰能指導我在這里做錯了什么?
uj5u.com熱心網友回復:
最好在函式開始時形成結果陣列。 numpy.append很慢。
def AppendSumNP(data, steps, dtype = np.float64 ):
result = np.zeros( len(data) steps, dtype = dtype )
# The result array is big enough for the whole result
result[ :len(data) ] = data
for j in range( len(data), len(data) steps ):
result[ j ] = result[:j].sum()
return result
此外,第二個和是第一個的兩倍,第三個是第二個的兩倍,依此類推,所以只求和一次,然后相乘。
def AppendMultNP(data, steps, dtype = np.float64 ):
result = np.zeros( len(data) steps, dtype = dtype )
result[ :len(data)] = data
total = result[:len(data)].sum()
for j in range( len(data), len(data) steps ):
result[ j ] = total
total *= 2
return result
這取決于資料串列的長度,但該Mult方法可以快幾倍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523796.html
下一篇:在for回圈R中遍歷兩個向量
