Numpy | Array Creation

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.
Example :

arr = [1, 2, 3, 4, 5]
arr1 = ["geeks", "for", "geeks"]
# Python program to create 
# an array

# Creating an array using list
    arr=[1, 2, 3, 4, 5]
    for i in arr:
        print(i)


Output:

1
2
3
4
5

 
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.
Example :

# Python code to demonstrate the working of 
# array()
 
# importing "array" for array operations
import array
 
# initializing array with array values
# initializes array with signed integers
arr = array.array('i', [1, 2, 3]) 

# printing original array
print ("The new created array is : ",end="")
for i in range (0,3):
    print (arr[i], end=" ")

print ("\r")

Output:

The new created array is : 1 2 3 1 5

 
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.

numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.


# Python Programming illustrating
# numpy.empty method

import numpy as geek

b = geek.empty(2, dtype = int)
print("Matrix b : \n", b)

a = geek.empty([2, 2], dtype = int)
print("\nMatrix a : \n", a)

c = geek.empty([3, 3])
print("\nMatrix c : \n", c)

Output :


Matrix b : 
 [         0 1079574528]

Matrix a : 
 [[0 0]
 [0 0]]

Matrix a : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

numpy.zeros(shape, dtype = None, order = ‘C’) : Return a new array of given shape and type, with zeros.


# Python Program illustrating
# numpy.zeros method

import numpy as geek

b = geek.zeros(2, dtype = int)
print("Matrix b : \n", b)

a = geek.zeros([2, 2], dtype = int)
print("\nMatrix a : \n", a)

c = geek.zeros([3, 3])
print("\nMatrix c : \n", c)

Output :

Matrix b : 
 [0 0]

Matrix a : 
 [[0 0]
 [0 0]]

Matrix c : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

 
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 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]]]

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 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 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 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]

 

Methods for array creation in Numpy

Function Description
empty() Return a new array of given shape and type, without initializing entries
empty_like() Return a new array with the same shape and type as a given array
eye() Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity() Return the identity array
ones() Return a new array of given shape and type, filled with ones
ones_like() Return an array of ones with the same shape and type as a given array
zeros() Return a new array of given shape and type, filled with zeros
zeros_like() Return an array of zeros with the same shape and type as a given array
full_like() Return a full array with the same shape and type as a given array.
array() Create an array
asarray() Convert the input to an array
asanyarray() Convert the input to an ndarray, but pass ndarray subclasses through
ascontiguousarray() Return a contiguous array in memory (C order)
asmatrix() Interpret the input as a matrix
copy() Return an array copy of the given object
frombuffer() Interpret a buffer as a 1-dimensional array
fromfile() Construct an array from data in a text or binary file
fromfunction() Construct an array by executing a function over each coordinate
fromiter() Create a new 1-dimensional array from an iterable object
fromstring() A new 1-D array initialized from text data in a string
loadtxt() Load data from a text file
arange() Return evenly spaced values within a given interval
linspace() Return evenly spaced numbers over a specified interval
logspace() Return numbers spaced evenly on a log scale
geomspace() Return numbers spaced evenly on a log scale (a geometric progression)
meshgrid() Return coordinate matrices from coordinate vectors
mgrid() nd_grid instance which returns a dense multi-dimensional “meshgrid
ogrid() nd_grid instance which returns an open multi-dimensional “meshgrid
diag() Extract a diagonal or construct a diagonal array
diagflat() Create a two-dimensional array with the flattened input as a diagonal
tri() An array with ones at and below the given diagonal and zeros elsewhere
tril() Lower triangle of an array
triu() Upper triangle of an array
vander() Generate a Vandermonde matrix
mat() Interpret the input as a matrix
bmat() Build a matrix object from a string, nested sequence, or array


My Personal Notes arrow_drop_up


Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.