【发布时间】:2017-09-11 05:46:09
【问题描述】:
在下面的代码中,我试图计算一组向量(numpy 向量)的频率和总和
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'matrix')原来是:
[[ 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 未被修改。
【问题讨论】:
-
见here