【问题标题】:+= with numpy.array object modifying original object+= 用 numpy.array 对象修改原始对象
【发布时间】: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 未被修改。

【问题讨论】:

标签: python numpy


【解决方案1】:

这一行:

this_data = the_data[index]

获取the_data 行的视图,而不是副本。视图由原始数组支持,并且改变视图将写入原始数组。

这一行:

sums[a_label] = this_data

将该视图插入到 sums 字典中,并且这一行:

sums[a_label] += this_data

通过视图对原始数组进行变异,因为+= 请求在对象可变时通过变异而不是通过创建新对象来执行操作。

【讨论】:

  • 太棒了。 sums[a_label] = np.copy(this_data) 是。我会尽快接受。
猜你喜欢
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 2015-02-03
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多