1

I have a 2D array containing the following numbers:

A = [[1, 5, 9, 42],
     [20, 2, 71, 0],
     [2, 44, 4, 9]]

I want to add a different constant value to each row without using loops. This value is a n*c with n being the current row and c being the constant. For example, c=100 so that:

B = [[1, 5, 9, 42],
     [120, 102, 171, 100],
     [202, 244, 204, 209]]

Any help would be greatly appreciated

Felipe Moser
  • 323
  • 4
  • 19

1 Answers1

0

You can do that as follows:

>>> A = [[1, 5, 9, 42],
...      [20, 2, 71, 0],
...      [2, 44, 4, 9]]
...      

>>> a = np.array(A)
>>> c = 100

>>> addto = np.arange(len(a))[:, None] * c

>>> a + addto
array([[  1,   5,   9,  42],
       [120, 102, 171, 100],
       [202, 244, 204, 209]])

np.arange(len(a)) gets you a 1-dimensional array of the indices, array([0, 1, 2]), which you can then multiply by c.

The hitch is that you then need to conform this to NumPy's broadcasting rules by expanding it's dimensionality:

>>> np.arange(len(a)).shape
(3,)

>>> np.arange(len(a))[:, None].shape
(3, 1)

You could also do something like np.linspace(0, 100*(len(a)-1), num=len(a))[:, None], but that is probably overkill here.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235