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.

Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501

1 Answers1

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,)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 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](http://stackoverflow.com/q/3337301/395857)), or directly use [numpy.matrix.A1](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.A1.html#numpy.matrix.A1). – Franck Dernoncourt Nov 17 '15 at 19:01