l have three arrays to append. Here a sample of my vectors :
V1=array([ 0.03317591, -0.01624349, -0.01151019])
V2=array([[ 0.06865846, -0.00223798],
[-0.02872752, -0.00369226],
[-0.02063454, -0.00231726]])
V3=
array([[ 0.01160267, 0.12610824, -0.01634712, 0.01217519],
[-0.00727594, -0.0501376 , -0.01641992, 0.00933081],
[-0.05305551, 0.01195211, 0.04031831, -0.04476306]])
in order to append the three vectors and get one vector l did the following :
new_v=np.hstack((V1,V2,V3))
l got the following error :
ValueError: all the input arrays must have same number of dimensions
However :
V2_V3=np.hstack((V2,V3))
works, it returns :
array([[ 0.06865846, -0.00223798, 0.01160267, 0.12610824, -0.01634712,
0.01217519],
[-0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
0.00933081],
[-0.02063454, -0.00231726, -0.05305551, 0.01195211, 0.04031831,
-0.04476306]])
What l would like to get is the following :
array([[0.03317591, 0.06865846, -0.00223798, 0.01160267, 0.12610824, -0.01634712,
0.01217519],
[-0.01624349, -0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
0.00933081],
[-0.01151019, -0.02063454, -0.00231726, -0.05305551, 0.01195211, 0.04031831,
-0.04476306]])
What is wrong with V1 ?
To use
np.hstack
, we need to convertV1
to2D
such that the lengths along the first axis for the three input arrays are the same -As alternatives, we can use
np.column_stack
ornp.concatenate
along the second axis on2D
convertedV1
alongwith others ornp.c_
-There's nothing wrong with V1 except that it's 1D while V2 and V3 are 2D. According to the docs for hstack, all the input arrays have to have the same shape on all except the second axis. V1 in your code doesn't have a second axis.
You can easily add an empty second axis to V1 during your call to hstack like this:
That should achieve your desired output.
Note: The
V1[:, None]
bit is one of three ways that NumPy has available to add empty dimensions to arrays. The other two areV1[:, np.newaxis]
and the function versionnp.expand_dims(V1, axis=1)
.You could use any of these in place of
V1[:, None]
in that line of code and it would work. Check out the docs for numpy.expand_dims for more on adding dimensions to arrays.