1

Reshape 3-D numpy array to 1-D array:

I would like to reshape a 3-D array that looks like this:

test_3d = np.array([[[0., 0.],
        [1., 1.]],

       [[2., 2.],
        [3., 3.]]])

To a 1-D array that looks like this:

array([0., 1., 2., 3., 0., 1., 2., 3.])

Flattening the array using test_3d.flatten() outputs:

array([0., 0., 1., 1., 2., 2., 3., 3.])

A combination of np.flatten/ravel and transpose functionalities work well for 2-D arrays, but for a 3-D array I get the following:

Input:
test_3d.T.flatten()
Output:
array([0., 2., 1., 3., 0., 2., 1., 3.])

Does anybody have any ideas?

1
  • 2
    transpose takes an order parameter.. Read its docs and experiment. Commented May 8, 2021 at 14:59

1 Answer 1

1

To present a more instructive example, I defined test_3d as:

test_3d = np.array(
    [[[0., 10.],
      [1., 11.]],
     [[2., 12.],
      [3., 13.]]])

(now you can tell apart both "initial" zeroes).

To get your expected result, run:

result = np.transpose(test_3d, (2, 0, 1)).flatten()

The result is:

array([ 0.,  1.,  2.,  3., 10., 11., 12., 13.])

An alternative solution is:

result = np.rollaxis(test_3d, 2).flatten()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.