Home > OS >  How it is internally arrange to 1 D
How it is internally arrange to 1 D

Time:11-17

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related