Question
Asked By – BFTM
Suppose I have a numpy array:
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
and I have a corresponding “vector:”
vector = np.array([1,2,3])
How do I operate on data
along each row to either subtract or divide so the result is:
sub_result = [[0,0,0], [0,0,0], [0,0,0]]
div_result = [[1,1,1], [1,1,1], [1,1,1]]
Long story short: How do I perform an operation on each row of a 2D array with a 1D array of scalars that correspond to each row?
Now we will see solution for issue: Numpy: Divide each row by a vector element
Answer
Here you go. You just need to use None
(or alternatively np.newaxis
) combined with broadcasting:
In [6]: data - vector[:,None]
Out[6]:
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
In [7]: data / vector[:,None]
Out[7]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
This question is answered By – JoshAdel
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0