gpt4 book ai didi

python - 在矩阵上使用 ufunc.at

转载 作者:太空狗 更新时间:2023-10-30 02:19:29 29 4
gpt4 key购买 nike

假设我有以下 numpy 数组:

>>> a=np.zeros(10)
>>> a
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

我可以使用 numpy.ufunc.at就地修改该数组:

>>> np.add.at(a, [0,3], 2)
>>> a
array([ 2., 0., 0., 2., 0., 0., 0., 0., 0., 0.])

如果我现在尝试使用矩阵,我认为该方法不起作用:

>>> m=np.zeros(16).reshape(4,4)
>>> m
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> np.add.at(m, [(0,0),(1,1)], 2)
>>> m
array([[ 0., 4., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])

基于提供 [(0,0),(1,1)] 的元组列表,我的期望是:

      [[ 2.,  0.,  0.,  0.],
[ 0., 2., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]

关于我在 numpy.ufunc.at 中用作索引列表以获取该矩阵的任何建议?

最佳答案

如果你想做多维索引,你不传递一个索引元组列表;你传递了一个索引列表(或索引数组)的元组。

indices = ([0, 1], [0, 1])
np.add.at(m, indices, 2)

indices[0] 给出了所有要修改的单元格的第一个坐标,indices[1] 给出了所有第二个坐标。这是一个例子:

In [10]: a = numpy.zeros([4, 4])
In [11]: a
Out[11]:
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
In [12]: indices = ([0, 3], [2, 1])
In [13]: numpy.add.at(a, indices, 2)
In [14]: a
Out[14]:
array([[ 0., 0., 2., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 2., 0., 0.]])

我不完全确定为什么会这样。我想一旦你掌握了它可能会更方便,或者它可能会以某种方式使规则在内部更加一致,但我没有足够的多维索引经验来说明这种或那种方式。

关于python - 在矩阵上使用 ufunc.at,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29617292/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com