Home > Blockchain >  Reducing the dimensions of an array in a list in Python
Reducing the dimensions of an array in a list in Python

Time:08-30

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)

CodePudding user response:

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.

  • Related