Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - numpy array concatenate: "ValueError: all the input arrays must have same number of dimensions"

How to concatenate these numpy arrays?

first np.array with a shape (5,4)

[[  6487    400 489580      0]
 [  6488    401 492994      0]
 [  6491    408 489247      0]
 [  6491    408 489247      0]
 [  6492    402 499013      0]]

second np.array with a shape (5,)

[  16.   15.   12.  12.  17. ]

final result should be

[[  6487    400    489580    0   16]
 [  6488    401    492994    0   15]
 [  6491    408    489247    0   12]
 [  6491    408    489247    0   12]
 [  6492    402    499013    0   17]]

I tried np.concatenate([array1, array2]) but i get this error

ValueError: all the input arrays must have same number of dimensions

What am I doing wrong?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To use np.concatenate, we need to extend the second array to 2D and then concatenate along axis=1 -

np.concatenate((a,b[:,None]),axis=1)

Alternatively, we can use np.column_stack that takes care of it -

np.column_stack((a,b))

Sample run -

In [84]: a
Out[84]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [85]: b
Out[85]: array([56, 70, 43, 19, 16])

In [86]: np.concatenate((a,b[:,None]),axis=1)
Out[86]: 
array([[54, 30, 55, 12, 56],
       [64, 94, 50, 72, 70],
       [67, 31, 56, 43, 43],
       [26, 58, 35, 14, 19],
       [97, 76, 84, 52, 16]])

If b is such that its a 1D array of dtype=object with a shape of (1,), most probably all of the data is contained in the only element in it, we need to flatten it out before concatenating. For that purpose, we can use np.concatenate on it too. Here's a sample run to make the point clear -

In [118]: a
Out[118]: 
array([[54, 30, 55, 12],
       [64, 94, 50, 72],
       [67, 31, 56, 43],
       [26, 58, 35, 14],
       [97, 76, 84, 52]])

In [119]: b
Out[119]: array([array([30, 41, 76, 13, 69])], dtype=object)

In [120]: b.shape
Out[120]: (1,)

In [121]: np.concatenate((a,np.concatenate(b)[:,None]),axis=1)
Out[121]: 
array([[54, 30, 55, 12, 30],
       [64, 94, 50, 72, 41],
       [67, 31, 56, 43, 76],
       [26, 58, 35, 14, 13],
       [97, 76, 84, 52, 69]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...