1

Can NumPy's flatten() return a 2D array?

I applied flatten() on an array of shape (12L, 54L), and I got a new array of shape (1L, 648L). Is that supposed to happen from time to time? If so, in which cases does that happen?

I use NumPy 1.9.2.

0

1 Answer 1

6

Unlike NumPy arrays, NumPy matrices are always 2D objects. So calling flatten on a NumPy matrix returns another 2D matrix, albeit one with shape (1, N):

In [112]: x = np.matrix(np.random.randint(10, size=(12,54))) In [116]: x.shape Out[116]: (12, 54) In [117]: x.flatten().shape Out[117]: (1, 648) 

If you convert the matrix to an array, then flatten will return a 1D array:

In [125]: np.asarray(x).flatten().shape Out[125]: (648,) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, good catch, the issue was indeed it was a matrix, not an array. I should have converted the matrix to an array first (Numpy matrix to array), or directly use numpy.matrix.A1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.