0

I have two numpy arrays, one is 2D of dimension (a, b) and the other is 1D of dimension a. I want to add the single value for each index of the 1D array to each member of the same index in the 2D array. Here's an example of what I'm trying to do:

import numpy as np
firstArr = np.random.random((5,6))
secondArr = np.linspace(0, 4, 5)

I know I can do what I want with the loop:

for i in range(5):
    firstArr[i] = firstArr[i] + secondArr[i]

But this is really not Pythonic, so it will no doubt take a looong time when I do it over millions of iterations.

What's the solution, here? Thanks!

Edit: I think I found the answer: use np.newaxis. This works, but I don't know if there's a more efficient way to do this. Here's how It would work:

arr = firstArr + secondArr[:, np.newaxis]

I'm leaving the question open for now because there's probably a more efficient way of doing this, but this at least works. It can also, per Numpy documentation, be written as:

arr = firstArr + secondArr[:, None]

I'll admit I don't know what exactly this does (still looking into that), so any guidance would be appreciated

HEP N008
  • 187
  • 8
  • I think you have `firstArr` and `secondArr` reversed in your examples. – MattDMo Sep 28 '20 at 19:36
  • @MattDMo I don't; at least, not for my intended functionality (I just copy/pasted the code in my question to make sure). I'm basically looking to have one, 2D array of values, and one, 1D array of biases that adds to those values in sequence. So the 1D array has to have its length be the number of rows in the 2D array, and each value in the 1D array is added to every value in the corresponding row. It works, but it's still ridiculously slow over a few million iterations. – HEP N008 Sep 29 '20 at 03:29
  • 1
    What's happening is "Broadcasting". See: https://numpy.org/doc/stable/user/basics.broadcasting.html – NNN Sep 29 '20 at 08:14

0 Answers0