Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

concatenate multiple numpy arrays in one array?

Assume I have many numpy array:

a = ([1,2,3,4,5])
b = ([2,3,4,5,6])
c = ([3,4,5,6,7])

and I want to generate a new 2-D array:

d = ([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]])

What should I code? I tried used:

d = np.concatenate((a,b),axis=0)
d = np.concatenate((d,c),axis=0)

It returns:

d = ([1,2,3,4,5,2,3,4,5,6,3,4,5,6,7])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned in the comments you could just use the np.array function:

>>> import numpy as np
>>> a = ([1,2,3,4,5])
>>> b = ([2,3,4,5,6])
>>> c = ([3,4,5,6,7])

>>> np.array([a, b, c])
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

In the general case that you want to stack based on a "not-yet-existing" dimension, you can also use np.stack:

>>> np.stack([a, b, c], axis=0)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

>>> np.stack([a, b, c], axis=1)  # not what you want, this is only to show what is possible
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...