I am trying to put 2 numpy arrays into a matrix/horizontally stack them. Each array is 76 elemets long, and I want the ending matrix to have 76 rows and 2 columns. I basically have a velocity/frequency model and want to have 2 columns with corresponding frequency/velocity values in each row.
Here is my code ('f' is frequency and 'v' the velocity values, previously already defined)
print(f.shape)
print(v.shape)
print(type(f))
print(type(v))
x = np.concatenate((f, v), axis = 1)
This returns
(76,)
(76,)
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
and an error about the concatenate line that says
AxisError: axis 1 is out of bounds for array of dimension 1
I've also tried hstack except for concatenat, as well as vstack and transposing .T, and have the same error. I've also tried using pandas but I need to use numpy because when I save it into a txt/dat file, pandas gives me an extra column with numbering that I need to not have.
CodePudding user response:
Your Problem is, that your vectors a one dimensional like in this example:
f_1d = np.array([1,2,3,4])
print(f_1d.shape)
> (4,)
As you can see only first dimension is given. So instead you could create your vectors like this:
f = np.expand_dims(np.array([1,2,3,4]), axis=1)
v = np.expand_dims(np.array([5,6,7,8]), axis=1)
print(f.shape)
print(v.shape)
>(4,1)
>(4,1)
As you may notice the second dimension is equal to one, but now your vector is represented in matrix form.
It is now possible to transpose the matrix-vectors:
f_t = f.T
v_t = v.T
print(f_t)
> (1,4)
Instead of using concatenate you could use vstack
or hstack
to create cleaner code:
x = np.hstack((f,v))
x_t = np.vstack((f_t,v_t))
print(x.shape)
print(x_t.shape)
>(4,2)
>(2,4)