Charlie Lam
Charlie Lam

Reputation: 111

How to add multiple values accumulatively to specific columns in python?

I guess this is a tricky question. I want to add some values accumulatively to some specific columns. Here's an example:

import numpy as np
A = np.random.rand(4,4)
B = np.random.rand(4,4)
[OUT]: A = array([[ 0.46472458,  0.00841153,  0.45631818,  0.42635626],
                  [ 0.37378943,  0.92900513,  0.47074237,  0.1790853 ],
                  [ 0.44455962,  0.38604916,  0.52130988,  0.17871398],
                  [ 0.74742154,  0.48381281,  0.25203475,  0.724025  ]])

[OUT]: B = array([[ 0.78213532,  0.31560444,  0.45251978,  0.19675709],
                  [ 0.06217241,  0.10009086,  0.65308642,  0.95227678],
                  [ 0.65643604,  0.20249389,  0.86545423,  0.62765881],
                  [ 0.61317907,  0.1636594 ,  0.28260492,  0.23835911]])

Now I want to add the second row and third row of B to the first column of A, and add the third row of B to the second column of A. Naively I tried this:

idx_col = np.array([0,0,1])
idx_row = np.array([1,2,2])
A[:, idx_col] += B[idx_row, :].T

But it didn't give me the result I want. The problem is python only adds the third row to the first column and completely ignores the second row to the first column.

[OUT]: array([[ 1.12116062,  0.66484757,  0.45631818,  0.42635626],
              [ 0.57628332,  1.13149902,  0.47074237,  0.1790853 ],
              [ 1.31001385,  1.25150339,  0.52130988,  0.17871398],
              [ 1.37508035,  1.11147162,  0.25203475,  0.724025  ]])

I realize I can do this with one for-loop, but the thing is I am doing an assignment and it requires the code to be fully vectorized (I know, it's very irritating). Also, this is a toy example, what I am actually implementing is, say A is 500-by-10, B is 500-by-500 and idx_col has a length of 100. So doing each operation separately really doesn't solve the problem. Any help would be great!

Upvotes: 0

Views: 300

Answers (1)

zephyr
zephyr

Reputation: 2332

I'm not sure if you need this to be more general, by if you only have 3 operations, why not make each their own line.

A[:,0] += B[1,:]
A[:,0] += B[2,:]
A[:,1] += B[2,:]

If you need to do this all on one line, it looks like the numpy function np.add.to does what you want. The description is as follows

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.

The only issue now is that I cannot determine how to handle multi-dimensional arrays. The documentation suggests it is possible though.

Upvotes: 1

Related Questions