Home > Enterprise >  How can I put two NumPy arrays into a matrix with two columns?
How can I put two NumPy arrays into a matrix with two columns?

Time:09-11

I am trying to put two NumPy arrays into a matrix or horizontally stack them. Each array is 76 elements 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 two 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 concatenate, 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 do not need to have.

CodePudding user response:

Your problem is that your vectors are one-dimensional, like in this example:

f_1d = np.array([1,2,3,4])
print(f_1d.shape)

> (4,)

As you can see, only the 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)
  • Related