. Advertisement .
..3..
. Advertisement .
..4..
Hi developer experts,
I have a small but frustrating use case, and so far, I couldn’t get my head around this problem & ideal solution. I am running my command and facing one problem with the valueerror: all the input array dimensions except for the concatenation axis must match exactly.
Below is the command I used:
[[ 6487 400 489580 0]
[ 6488 401 492994 0]
[ 6491 408 489247 0]
[ 6491 408 489247 0]
[ 6492 402 499013 0]]
[ 16. 15. 12. 12. 17. ]
[[ 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]]
When I run it, I get the following error:
ValueError: all the input arrays must have same number of dimensions
I am looking forward to gaining some knowledge from all experts.
Thank you, guys!
We need
Alternativ,
Test run
If np.concatenate
to use. To do this, extend the second array 2D
to 2D
, and then concatenate with axis=1
.
np.concatenate((a,b[:,None]),axis=1)
np.column_stack
can take care of it.
np.column_stack((a,b))
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]])
b
is 1D
array dtype=object
, with a shape (1,)
, then most likely all data is in the first element. Flatten it before concatenating. We can also use np.concatenate
to accomplish this. To illustrate the point, here’s a sample run.
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]])
The cause: An axis in the arrays which is concatenated in one element of your dataset has different lengths.
Solution: We need
np.concatenate
to use. To do this, extend the second array2D
to2D
, and then concatenate withaxis=1
.Alternativ,
np.column_stack
can take care of it.Test run
If
b
is1D
arraydtype=object
, with a shape(1,)
, then most likely all data is in the first element. Flatten it before concatenating. We can also usenp.concatenate
to accomplish this. To illustrate the point, here’s a sample run.np.c_
is also available