Reshaping array

We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, …, aN). We can reshape and convert it into another array with shape (b1, b2, b3, …, bM).
The only required condition is: a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM . (i.e original size of array remains unchanged.)

numpy.reshape(array, shape, order = ‘C’) : Shapes an array without changing data of array.

Python
# Python Program illustrating
# numpy.reshape() method

import numpy as geek

array = geek.arange(8)
print("Original array : \n", array)

# shape array with 2 rows and 4 columns
array = geek.arange(8).reshape(2, 4)
print("\narray reshaped with 2 rows and 4 columns : \n", array)

# shape array with 2 rows and 4 columns
array = geek.arange(8).reshape(4 ,2)
print("\narray reshaped with 2 rows and 4 columns : \n", array)

# Constructs 3D array
array = geek.arange(8).reshape(2, 2, 2)
print("\nOriginal array reshaped to 3D : \n", array)

Output :

Original array : 
[0 1 2 3 4 5 6 7]

array reshaped with 2 rows and 4 columns :
[[0 1 2 3]
[4 5 6 7]]

array reshaped with 2 rows and 4 columns :
[[0 1]
[2 3]
[4 5]
[6 7]]

Original array reshaped to 3D :
[[[0 1]
[2 3]]

[[4 5]
[6 7]]]

Returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop) To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.
arange returns evenly spaced values within a given interval. step size is specified.
linspace returns evenly spaced values within a given interval. num no. of elements are returned.

arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop)

Python
# Python Programming illustrating
# numpy.arange method

import numpy as geek

print("A\n", geek.arange(4).reshape(2, 2), "\n")

print("A\n", geek.arange(4, 10), "\n")

print("A\n", geek.arange(4, 20, 3), "\n")

Output :

A
[[0 1]
[2 3]]

A
[4 5 6 7 8 9]

A
[ 4 7 10 13 16 19]


numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) : Returns number spaces evenly w.r.t interval. Similiar to arange but instead of step it uses sample number.


Python
# Python Programming illustrating
# numpy.linspace method

import numpy as geek

# restep set to True
print("B\n", geek.linspace(2.0, 3.0, num=5, retstep=True), "\n")

# To evaluate sin() in long range 
x = geek.linspace(0, 2, 10)
print("A\n", geek.sin(x))

Output :

B
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

A
[ 0. 0.22039774 0.42995636 0.6183698 0.77637192 0.8961922
0.9719379 0.99988386 0.9786557 0.90929743]

Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order.

numpy.ndarray.flatten(order = ‘C’) : Return a copy of the array collapsed into one dimension.

Python
# Python Program illustrating
# numpy.flatten() method

import numpy as geek

array = geek.array([[1, 2], [3, 4]])

# using flatten method
array.flatten()
print(array)

#using fatten method 
array.flatten('F')
print(array)

Output :

[1, 2, 3, 4]
[1, 3, 2, 4]

Numpy | Array Creation

In this article, we are going to explore numpy array creation technique.

Table of Content

  • Array creation using List :
  • Array creation using array functions
  • Methods for array creation in Numpy

Similar Reads

Array creation using List :

Arrays are used to store multiple values in one single variable.Python does not have built-in support for Arrays, but Python lists can be used instead....

Array creation using array functions

array(data type, value list) function is used to create an array with data type and value list specified in its arguments.np.zeros...

Array creation using numpy methods

NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. For example: np.zeros,np.empty etc....

Reshaping array

We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, …, aN). We can reshape and convert it into another array with shape (b1, b2, b3, …, bM).The only required condition is: a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM . (i.e original size of array remains unchanged.)...

Methods for array creation in Numpy

FunctionDescriptionempty()Return a new array of given shape and type, without initializing entriesempty_like()Return a new array with the same shape and type as a given arrayeye()Return a 2-D array with ones on the diagonal and zeros elsewhere.identity()Return the identity arrayones()Return a new array of given shape and type, filled with onesones_like()Return an array of ones with the same shape and type as a given arrayzeros()Return a new array of given shape and type, filled with zeroszeros_like()Return an array of zeros with the same shape and type as a given arrayfull_like()Return a full array with the same shape and type as a given array.array()Create an arrayasarray()Convert the input to an arrayasanyarray()Convert the input to an ndarray, but pass ndarray subclasses throughascontiguousarray()Return a contiguous array in memory (C order)asmatrix()Interpret the input as a matrixcopy()Return an array copy of the given objectfrombuffer()Interpret a buffer as a 1-dimensional arrayfromfile()Construct an array from data in a text or binary filefromfunction()Construct an array by executing a function over each coordinatefromiter()Create a new 1-dimensional array from an iterable objectfromstring()A new 1-D array initialized from text data in a stringloadtxt()Load data from a text filearange()Return evenly spaced values within a given intervallinspace()Return evenly spaced numbers over a specified intervallogspace()Return numbers spaced evenly on a log scalegeomspace()Return numbers spaced evenly on a log scale (a geometric progression)meshgrid()Return coordinate matrices from coordinate vectorsmgrid()nd_grid instance which returns a dense multi-dimensional “meshgridogrid()nd_grid instance which returns an open multi-dimensional “meshgriddiag()Extract a diagonal or construct a diagonal arraydiagflat()Create a two-dimensional array with the flattened input as a diagonaltri()An array with ones at and below the given diagonal and zeros elsewheretril()Lower triangle of an arraytriu()Upper triangle of an arrayvander()Generate a Vandermonde matrixmat()Interpret the input as a matrixbmat()Build a matrix object from a string, nested sequence, or array...

Contact Us