2017-04-14 167 views
0

在下面的代碼=,我試圖計算的頻率和一組向量總和(numpy的載體)+與numpy.array對象修改原始對象

def calculate_means_on(the_labels, the_data): 
    freq = dict(); 
    sums = dict(); 
    means = dict(); 
    total = 0; 
    for index, a_label in enumerate(the_labels): 
     this_data = the_data[index]; 
     if a_label not in freq: 
      freq[a_label] = 1; 
      sums[a_label] = this_data; 
     else: 
      freq[a_label] += 1; 
      sums[a_label] += this_data; 

假設the_data(一個numpy的'矩陣')最初是:

[[ 1. 2. 4.] 
[ 1. 2. 4.] 
[ 2. 1. 1.] 
[ 2. 1. 1.] 
[ 1. 1. 1.]] 

運行上述代碼之後,the_data變爲:

[[ 3. 6. 12.] 
[ 1. 2. 4.] 
[ 7. 4. 4.] 
[ 2. 1. 1.] 
[ 1. 1. 1.]] 

這是爲什麼?我已經推斷它到行sums[a_label] += this_data;,因爲當我將其更改爲sums[a_label] = sums[a_label] + this_data;它表現如預期;即,the_data未被修改。

+1

看到[這裏](http://stackoverflow.com/questions/12905338/python-difference-between-x-x1-and-x-1) –

回答

4

這條線:

this_data = the_data[index] 

需要一個視圖,而不是一個拷貝的the_data一排。該視圖由原始數組支持,並且對該視圖進行變異將寫入原始數組。

這行:該操作由執行

sums[a_label] += this_data 

變異通過視圖原始數組,因爲+=請求:

sums[a_label] = this_data 

插入該查看到sums字典,並且該線突變,而不是通過創建一個新的對象,當對象是可變的。

+0

太棒了。 '總和[a_label] = np.copy(this_data)'它是。只要它讓我接受,就會接受。 –