在矩阵上使用ufunc.at [英] Using ufunc.at on matrix

查看:78
本文介绍了在矩阵上使用ufunc.at的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下numpy数组:

Suppose I have the following numpy array:

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

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

I can use numpy.ufunc.at to modify that array in place:

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

如果我现在尝试使用矩阵,那么我假设是该方法不起作用:

If I now try on a matrix, what I assume to be the method does not work:

>>> 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)]元组列表的期望是:

My expectation based on supplying the list of tuples of [(0,0),(1,1)] would be:

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

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

Any suggestions on what I use as a list of indices in numpy.ufunc.at to get that matrix?

推荐答案

如果要进行多维索引编制,则不传递索引元组列表;您传递索引列表(或索引数组)的元组.

If you want to do multidimensional indexing, you don't pass a list of index tuples; you pass a tuple of index lists (or index arrays).

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

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

indices[0] gives all the first coordinates of the cells you want to modify, and indices[1] gives all the second coordinates. Here's an example:

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.]])

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

I'm not entirely sure why it works this way. I suppose it might be more convenient once you've gotten the hang of it, or it might make the rules more internally consistent somehow, but I don't have enough experience with multidimensional indexing to say one way or another.

这篇关于在矩阵上使用ufunc.at的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆