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