Reputation: 161
I have the following numpy array:
X = [[1],
[2],
[3],
[4]]
Y = [[5],
[6],
[7],
[8]]
Z = [[9],
[10],
[11],
[12]]
I would like to get the following output:
H = [[1,5,9],
[2,6,10],
[3,7,11]
[4,8,12]]
Is there a way get this result using numpy.reshape?
Upvotes: 0
Views: 2623
Reputation: 61355
How about this (faster) solution?
In [16]: np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
Out[16]:
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
Efficiency (descending order)
# proposed (faster) solution
In [17]: %timeit np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
The slowest run took 7.40 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.36 µs per loop
# Other solutions
In [18]: %timeit np.column_stack((x, y, z))
The slowest run took 5.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 9.18 µs per loop
In [19]: %timeit np.hstack((x, y, z))
The slowest run took 4.49 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 16 µs per loop
In [20]: %timeit np.reshape((x,y,z),(3,4)).T
10000 loops, best of 3: 21.6 µs per loop
In [20]: %timeit np.c_[x, y, z]
10000 loops, best of 3: 55.9 µs per loop
Upvotes: 1
Reputation: 53029
And don't forget np.c_
(I don't see the need for np.reshape
):
np.c_[X,Y,Z]
# array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])
Upvotes: 1
Reputation: 221564
You can use np.column_stack
-
np.column_stack((X,Y,Z))
Or np.concatenate
along axis=1
-
np.concatenate((X,Y,Z),axis=1)
Or np.hstack
-
np.hstack((X,Y,Z))
Or np.stack
along axis=0
and then do multi-dim transpose -
np.stack((X,Y,Z),axis=0).T
Reshape applies on an array, not to stack or concatenate arrays together. So, reshape
alone doesn't make sense here.
One could argue using np.reshape
to give us the desired output, like so -
np.reshape((X,Y,Z),(3,4)).T
But, under the hoods its doing the stacking operation, which AFAIK is something to convert to array with np.asarray
-
In [453]: np.asarray((X,Y,Z))
Out[453]:
array([[[ 1],
[ 2],
[ 3],
[ 4]],
[[ 5],
[ 6],
[ 7],
[ 8]],
[[ 9],
[10],
[11],
[12]]])
We just need to use multi-dim transpose
on it, to give us a 3D
array version of the expected output -
In [454]: np.asarray((X,Y,Z)).T
Out[454]:
array([[[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]]])
Upvotes: 4