0

Let's say I have a square matrix with 20 lines and 20 columns. Using NumPy, what should I do to transform this matrix into a 1D array with a single line and 400 columns (that is, 20.20 = 400, all in one line)?

So far, I've tried:

1) array = np.ravel(matrix)

2) array = np.squeeze(np.asarray(matrix))

But when I print array, it's still a square matrix.

7
  • 1
    Try array = matrix.flatten() Commented Aug 28, 2018 at 15:51
  • 2
    or matrix.reshape(-1,) Commented Aug 28, 2018 at 15:52
  • 1
    Also try np.reshape() it should work(more detail [docs.scipy.org/doc/numpy/reference/generated/…). Commented Aug 28, 2018 at 15:53
  • If you're using a numpy matrix, then switch to an ordinary ndarray. The matrix object is deprecated. array = matrix.ravel() should work if matrix is an ndarray. Commented Aug 28, 2018 at 15:56
  • If ravel doesn't work, then there's something unusual about matrix. Tell us its shape, dtype, and whether it is np.matrix or not. Commented Aug 28, 2018 at 15:57

1 Answer 1

3

Use the reshape method: array = matrix.reshape((1,400)). This works for both Numpy Array and Matrix types.

UPDATE: As sacul noted, matrix.reshape(-1) is more general in terms of dimensions.

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.