简体   繁体   中英

Add elements of array to each column of matrix using numpy

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?

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:

  1. Transpose: np.ndarray.T
  2. Expand dimensions: np.expand_dims
  3. np.add

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]]

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM