1

I am reshaping the array in a list Test from (1, 3, 3) to (3, 3). How do I reshape for a more general form, say for a very numpy array from (1, n, n) to (n, n)?

import numpy as np

Test = [np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])]
Test = Test[0].reshape(3, 3)
3
  • "I am reshaping the list Test from (1,3,3) to (3,3)." No, you are not. You are reshaping the Numpy Array inside the list. Commented Aug 29, 2022 at 10:57
  • 1
    In your case Test = Test[0][0] would give you (n,n) for any (1,n,n) Commented Aug 29, 2022 at 10:58
  • 1
    I think you are looking for np.squeeze() Commented Aug 29, 2022 at 10:59

1 Answer 1

2

The list is not relevant. The simplest way to reshape to the smallest valid shape is squeeze:

Test = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
assert Test.shape == (1, 3, 3)
Test = Test.squeeze()
assert Test.shape == (3, 3)

By smallest valid size, I mean to eliminate all dimensions that have length 1. You can customize it to only pick specific axes to zero out, but in practice, I find the default behavior is most useful. A super-useful feature of squeeze is that it's idempotent. You can keep "squeezing" an array as many times as you want.

Bonus: The same function exists in pandas pd.DataFrame.squeeze where it gives you a pd.Series from a single column pd.DataFrame.

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.