2

I have this array:

import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
first_stacked = np.stack((x, y, z, w), axis=0)
print(first_stacked.shape)  # (4, 3, 2, 2)

And I want to convert into this array:

import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
last_stacked = np.stack((x, y, z, w), axis=-1)
print(last_stacked.shape)  # (3, 2, 2, 4)

I tried this:

new_stacked = [i for i in first_stacked]
new_stacked = np.stack(new_stacked, axis=-1)
other_stacked = np.stack(first_stacked, axis=-1)
print(new_stacked.shape)
print(other_stacked.shape)
print(np.array_equal(new_stacked, last_stacked))
print(np.array_equal(new_stacked, other_stacked))

Output:

(3, 2, 2, 4)
(3, 2, 2, 4)
False
True

So neither of my two attempts work. What am I missing? Can it be done with just a reshape on the first_stacked? I worry if my arrays are too big, if it's more than a reshape, it could be a problem, though maybe my fears are unfounded.

Edit: I was randomizing the x,y,z,w arrays twice in the Jupyter Notebook and the second values were obviously not equal to the first. I apologize. Though if there's a better way to do it, I'm still interested.

So, the working code:

import numpy as np
shape = (3, 2, 2)
x = np.round(np.random.rand(*shape) * 100)
y = np.round(np.random.rand(*shape) * 100)
z = np.round(np.random.rand(*shape) * 100)
w = np.round(np.random.rand(*shape) * 100)
first_stacked = np.stack((x, y, z, w), axis=0)
print(first_stacked.shape)
last_stacked = np.stack((x, y, z, w), axis=-1)
print(last_stacked.shape)

new_stacked = [i for i in first_stacked]
new_stacked = np.stack(new_stacked, axis=-1)
other_stacked = np.stack(first_stacked, axis=-1)
print(new_stacked.shape)
print(other_stacked.shape)
print(np.array_equal(new_stacked, last_stacked))
print(np.array_equal(new_stacked, other_stacked))

Output:

(4, 3, 2, 2)
(3, 2, 2, 4)
(3, 2, 2, 4)
(3, 2, 2, 4)
True
True
JoeP
  • 23
  • 3

1 Answers1

1

You can use numpy.moveaxis to move the first axis to the last position.

np.moveaxis(first_stacked, 0, -1)

Or you can roll the axis into the desired position

np.rollaxis(first_stacked, 0, first_stacked.ndim)
miradulo
  • 28,857
  • 6
  • 80
  • 93
  • Oh, nice. I didn't know this. This is exactly what I wanted. ty – JoeP Jun 17 '18 at 21:13
  • What's the difference between the two? – JoeP Jun 17 '18 at 21:25
  • @JoeP I advise you read [Reason why numpy rollaxis is so confusing?](https://stackoverflow.com/questions/29891583/reason-why-numpy-rollaxis-is-so-confusing). `moveaxis` is a little easier to use. – miradulo Jun 17 '18 at 21:26