python - 矢量化 - 添加没有循环的 numpy 数组?

标签 python arrays numpy vectorization

所以我有以下 numpy 数组:

c = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12]])
X = array([[10, 15, 20,  5],
           [ 1,  2,  6, 23]])
y = array([1, 1])

我正在尝试添加每个 1x4行在 X数组到 c 中的一列。 y array 指定哪一列。上面的示例意味着我们要在 X 中添加两行数组到列1 c.也就是说,我们应该期望以下结果:

     c = array([[ 1,  2+10+1,  3],  =  array([[ 1,  13,  3],
                [ 4,  5+15+2,  6],            [ 4,  22,  6],
                [ 7,  8+20+6,  9],            [ 7,  34,  9],
                [10, 11+5+23, 12]])           [10,  39, 12]])  

有谁知道如何在没有任何循环的情况下做到这一点?我试过c[:,y] += X但似乎这只添加了第二行 X前往栏目1c一次。话虽如此,应该指出的是y不一定必须是[1,1] ,也可以是[0,1] 。在本例中,我们将添加第一行 X前往栏目0c第二行X前往栏目1c .

最佳答案

当我看到你想要的计算时,我的第一个想法就是将 X 的 2 行相加。 ,并将其添加到 c 的第二列:

In [636]: c = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12]])

In [637]: c[:,1]+=X.sum(axis=0)

In [638]: c
Out[638]: 
array([[ 1, 13,  3],
       [ 4, 22,  6],
       [ 7, 34,  9],
       [10, 39, 12]])

但是如果我们想从像 y 这样的通用索引开始工作,我们需要一个特殊的bufferless操作 - 即 y 中是否有重复项:

In [639]: c = array([[ 1,  2,  3],
           [ 4,  5,  6],
           [ 7,  8,  9],
           [10, 11, 12]])

In [641]: np.add.at(c,(slice(None),y),X.T)

In [642]: c
Out[642]: 
array([[ 1, 13,  3],
       [ 4, 22,  6],
       [ 7, 34,  9],
       [10, 39, 12]])

您需要查找.at在 numpy 文档中。

在 Ipython 中 add.at?向我展示了包含以下内容的文档:

Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once. For example, a[[0,0]] += 1 will only increment the first element once because of buffering, whereas add.at(a, [0,0], 1) will increment the first element twice.

使用不同的y它仍然有效

In [645]: np.add.at(c,(slice(None),[0,2]),X.T)

In [646]: c
Out[646]: 
array([[11,  2,  4],
       [19,  5,  8],
       [27,  8, 15],
       [15, 11, 35]])

关于python - 矢量化 - 添加没有循环的 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37846676/

相关文章:

python - Flask 中的 JSON 数据是字符串还是字典?

python - 在一个主列和另一个可选列之间选择 pandas 中的 bool 值

python - 在花式索引时使用范围?

python - Numpy 矩阵乘法错误

python - 将给定日期后的日期时间转换为分钟

python - 重复列表中的 i - n 次

java - Android 批量插入或忽略 JSONArray

javascript - 两个数组的求和\相加(特别)

c - 如何对表示时间表的数组结构对象进行排序

python - 数字是 float64 吗?