简体   繁体   中英

What is this called: creating numpy matrix from several vectors

I have 4 individual numpy vectors with the shape (10, ), and I want to join them together to form a matrix (10, 4).

What is this transformation called?

It's called stack .

> import numpy as np
> a = np.arange(10)
> b = np.stack((a, a, a, a), axis=1)
> np.shape(b)
(10, 4)
> b
array([[0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3],
       [4, 4, 4, 4],
       [5, 5, 5, 5],
       [6, 6, 6, 6],
       [7, 7, 7, 7],
       [8, 8, 8, 8],
       [9, 9, 9, 9]])

You could also (in this case) use eg np.array([a, a, a, a]).T .

You could also create a new array from the collection and transpose the result.

np.random.seed(0)
a1 = np.random.randint(1, 10, 10)
a2 = np.random.randint(1, 10, 10)
a3 = np.random.randint(1, 10, 10)
a4 = np.random.randint(1, 10, 10)

>>> np.array([a1, a2, a3, a4]).T
array([[6, 7, 9, 2],
       [1, 9, 5, 4],
       [4, 9, 4, 4],
       [4, 2, 1, 4],
       [8, 7, 4, 8],
       [4, 8, 6, 1],
       [6, 8, 1, 2],
       [3, 9, 3, 1],
       [5, 2, 4, 5],
       [8, 6, 9, 8]])

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