Reputation: 83
I have a matrix 3x3 and array with 3 values and I want to add each value of my array to each column of the matrix, so for example, if I have matrix like:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
and array [1, 2, 3]
I want to get a result like
[[2, 3, 4],
[6, 7, 8],
[10, 11, 12]]
But now when I'm trying to add my array to matrix it adds it by columns, so I get this:
[[2, 4, 6],
[5, 7, 9],
[8, 10, 12]]
And I can not change the axis to add operation or find method to do such calculation. Maybe I need to do it in a few steps? Or I just missed something?
Upvotes: 2
Views: 1398
Reputation: 15872
Use transpose
:
>>> arr1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr2 = np.array([1, 2, 3])
>>> (arr1.T + arr2).T
array([[ 2, 3, 4],
[ 6, 7, 8],
[10, 11, 12]])
Or make arr2
a column matrix by expanding dimension:
>>> arr1 + arr2[:,None]
array([[ 2, 3, 4],
[ 6, 7, 8],
[10, 11, 12]])
If both are list
s:
>>> arr1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> arr2 = [1, 2, 3]
np.add(arr1, np.expand_dims(arr2, 1))
References:
np.ndarray.T
np.expand_dims
np.add
Upvotes: 2
Reputation: 2367
You can use the numpy.newaxis
operator, as shown in Code 1
(explained in a grate book - Python Data Science Handbook by Jake VanderPlas) to achieve the desired result:
Code 1:
import numpy as np
A = np.array(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
)
x = np.array([1, 2, 3])
A + x[np.newaxis:]
Output:
Out:
array([[ 2, 4, 6],
[ 5, 7, 9],
[ 8, 10, 12]])
It also will be the most efficient way to accomplish this task in terms of speed and memory consumption, if you are dealing with numerical data in large datasets, because numpy
is much more efficient than python.list
object, due to numpy
s' type awareness.
Cheers.
Upvotes: 1
Reputation: 885
an elegant solution would be
A
>>> [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B
>>> [1, 2, 3]
ans = A + B[:, None]
ans
>>> [[ 2, 3, 4],
[ 6, 7, 8],
[10, 11, 12]]
Upvotes: 1
Reputation: 95
one way to do it would be the following.
array1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
array2 = [1, 2, 3]
for i in range(0, len(array2)):
for j in range(0, len(array1[i-1])):
array1[i][j] += array2[i]
print(array1)
Upvotes: -1