1

I am reading over the internet regarding numpy, got stuck at this point

How the array is getting converted to 1 D

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

newa = arr.reshape(-1)

print(newa)

Output : 1,2,3,4,5,6

  • 1
    Because you supply the `reshape` method with just one argument: one argument, one resulting dimension. – 9769953 Nov 16 '21 at 13:55
  • Are you interested n the technical details how it works that the array becomes 1d? Or are you asking how reshape works and why it gives you a 1d array when you tell it you want a shape of -1? Your comments on the other question got me wondering. – Lukas S Nov 16 '21 at 14:20
  • @user2640045 : how reshape works and why it gives a 1d array want to know –  Nov 16 '21 at 14:31
  • 1
    @xawefog : May be this could help you : https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape – codeholic24 Nov 16 '21 at 14:39

2 Answers2

0

Look at the documentation:

newshape : int or tuple of ints. The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

Bricam
  • 71
  • 5
0

Why does reshape give you a 1d array for arr.reshape(-1)?

Well usually you give reshape a tuple of sizes you want your array to be reshaped to. E.g. if you have an array with 10 elements and you do arr.reshape((5,2)) it gives you a 2d array that is 5 by 2.

arr = np.arange(10) -> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr.reshape((5,2)) -> array([[0, 1],
                             [2, 3],
                             [4, 5],
                             [6, 7],
                             [8, 9]])

If you had given reshape numbers that don't multiply to 10 like 3 and 5 it would give you an error. But if you know all but one of the dimensions and want numpy to figure out what to pick for the last one so it works out you can put a -1 there. E.g. arr.reshape((5,-1)) and arr.reshape((-1,2)) give you exactly the same result as arr.reshape((5,2)). Notice that sometimes it still does not work out even with -1. E.g. arr.reshape((3,-1)) would raise an error. It's not possible to make a 3 by something array out of 10 numbers.

So if you do arr.reshape(-1) it means you want a 1d array containing all your numbers.

Lukas S
  • 3,212
  • 2
  • 13
  • 25