[英]How to divide one columns value by a previous rows column(not the same column) and add the result as a new dimension to a numpy array?
[英]How to subtract the previous rows column from current column and create a new dimension in the array with this value using numpy?
我想做的是獲取當前數組,並從當前行列值中減去前幾行的值。 我也想獲取結果並將其作為新維度添加到數組中。
示例數組:
[[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]]
可以說我想在第4列中執行此操作,因此我希望輸出是一個看起來像這樣的數組:
[[1,2,4,7,9,15,0], [3, 4,3,5,10,2,-2], [5,6,56,7,20,1,2]]
謝謝
您可以結合使用np.diff
和concatenate
選項來執行此操作,如下所示:
import numpy as np
myarray = np.array([[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]])
#your differences appears to be wraparound, so we repeat the last row at the top:
myarray_wrap = np.vstack((myarray[-1],myarray))
#this gets the diffs for all columns:
column_diffs = np.diff(myarray_wrap, axis=0)
#now we add in only the the column_diff that we want, at the end:
print np.hstack((myarray, column_diffs[:,3].reshape(-1,1)))
#Output:
[[ 1 2 4 7 9 15 0]
[ 3 4 3 5 10 2 -2]
[ 5 6 56 7 20 1 2]]
此Python代碼應該可以解決您的問題。
previous = None
for row in rows:
current = row[4]
row.append( 0 if previous == None else current - previous )
previous = current
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.