简体   繁体   中英

Python add 1d array to 2d array by column

I have a 1d array and 2d array

a = [4,7,10]
b = [[1,2,3],[4,5,6],[7,8,9]]
a.shape = (2,)
b.shape = (3,3)

I want:

c = [[1,2,3,4],[4,5,6,7],[7,8,9,10]]
c.shape = (3,4)

I tried np.vstack , np.concenrate but all failed

You can use numpy.column_stack :

>>> np.column_stack([b,a])
array([[ 1,  2,  3,  4],
       [ 4,  5,  6,  7],
       [ 7,  8,  9, 10]])

When you try somethings and fail, you should show the work and error. You might learn something in the process.

In [19]: a = np.array([4,7,10])
    ...: b = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [20]: np.vstack((a,b))
Out[20]: 
array([[ 4,  7, 10],
       [ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9]])

vstack works, but adds the V ertically, as the name implies.

To join them horizontally we need to specify axis 1:

In [28]: np.concatenate((b,a), axis=1)
Traceback (most recent call last):
  File "<ipython-input-28-52d167b3d573>", line 1, in <module>
    np.concatenate((b,a), axis=1)
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

vstack joins them vertically (axis 0), and adjusts dimensions as needed.

But it's easy to add a dimension to a . reshape can do it, also:

In [29]: a[:,None].shape
Out[29]: (3, 1)

In [30]: np.concatenate((b,a[:,None]), axis=1)
Out[30]: 
array([[ 1,  2,  3,  4],
       [ 4,  5,  6,  7],
       [ 7,  8,  9, 10]])

If you look at the code for column_stack as suggested in the other answer, you'll see that it does this - adds dimensions as needed.

The core join function is concatenate . Learn to adjust dimensions, and you can doing all kinds of joins without remembering all the different names.

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