![](/img/trans.png)
[英]How to update the array value and perform the same operation for the new values
[英]Why is the change of values in one array is affecting the value on another array (with exact same values) that isn't involved in the operation?
當我運行命令“ negative_only [negative_only> 0] = 0”(應該在數組“ negative_only”上使正值= 0)時,類似數組(“ positive_only”)上的值也會更改。 為什么會這樣呢? 我正在使用Python 3.7(Windows 10 / Spyder IDE)。
下面是操縱兩個數組的代碼。 “ long_dollars_ch”是〜2700 x 60的數組,其中包含一些正值,一些負值和很多零。 此代碼是循環在數組“ long_dollars_ch”的每一行中循環的一部分。
# calculations to isolate top contributors to NAV change for audits
top_check = 3 # number of top values changes to track
# calculate dollar change (for longs), and create array with most positive/negative values
long_dollars_ch[c_day,:] = long_shares[c_day,:]*hist_prices_zeros[c_day,:]-long_shares[c_day,:]*hist_prices_zeros[c_day-1,:]
positive_only = long_dollars_ch[c_day,:]
positive_only[positive_only<0]=0 #makes non-positive values zero
idx = np.argsort(positive_only) #creat index representing sorted values for only_positive for c_day
non_top_vals = idx[:-top_check]
negative_only = long_dollars_ch[c_day,:]
negative_only[negative_only>0]=0 #makes non-negative values zero
idx = np.argsort(negative_only) #creat index representing sorted values for only_negative for c_day
non_bottom_vals = idx[:-top_check]
# create array that shows the most positive/negative dollar change for "top-check" securities
long_dollars_ch_pos[c_day,:] = positive_only
long_dollars_ch_pos[c_day,:][non_top_vals] *= 0
long_dollars_ch_neg[c_day,:] = negative_only
long_dollars_ch_neg[c_day,:][non_bottom_vals] *= 0
此代碼的目的是創建兩個數組。 對於原始數組“ long_dollars_ch”的每一行,一個僅具有頂部“ top_check”正值(如果有),另一個具有底部“ top_check”負值(如果有)。 但是,似乎Python正在考慮將“ positive_only”和“ negative_only”視為相同的“變量”。 因此,其中一個操作會影響另一個內部的值(這不是該操作的一部分)。
它很簡單。
在numpy np.array x = np.array y
您不復制array :)
您引用數組x。
換句話說,使用“ =”后,您將沒有兩個數組。 您仍然有一個數組x,以及對該數組的引用(y是該引用)。
positive_only = long_dollars_ch[c_day,:]
.
.
,
negative_only = long_dollars_ch[c_day,:]
不要復制long_dollars_ch,而僅對其進行引用。 您需要使用復制方法或其他方法(numpy提供了其中的幾種方法)使其起作用。 這是一個文檔
編輯:我發布了錯誤的鏈接,現在可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.