Open In App

Numpy - Array Creation

Last Updated : 24 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Numpy Arrays are grid-like structures similar to lists in Python but optimized for numerical operations. The most straightforward way to create a NumPy array is by converting a regular Python list into an array using the np.array() function.

Let's understand this with the help of an example:

import numpy as np

# One-dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)

# Two-dimensional array
arr2 = np.array([[1, 2], [3, 4]])
print(arr2)

Output
[1 2 3 4 5]
[[1 2]
 [3 4]]

Creating Arrays with Specific Values

For assigning a specific values. NumPy provides several function to create arrays filled with zeros, ones, or a specific constant value.

  • Zeros Array: np.zeros() function creates an array filled with zeros. It requires the shape of the array as a parameter.

Example:

import numpy as np

# 3x4 array filled with zeros
arr_zero = np.zeros((3, 4))  
print(arr_zero)

Output
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
  • Ones Array: np.ones() creates an array filled with ones.

Example:

import numpy as np 

# 2x3 array filled with ones
arr_one = np.ones((2, 3))  
print(arr_one)

Output
[[1. 1. 1.]
 [1. 1. 1.]]
  • Full Array : np.full() function allows you to create an array filled with a specific value.

Example:

import numpy as np 

# 2x2 array filled with 7
arr_full = np.full((2, 2), 7)
print(arr_full)

Output
[[7 7]
 [7 7]]

Creating Arrays with Random Values

NumPy also has functions for generating arrays with random values, useful for simulations and testing.

  • Random Float Array : np.random.rand() function generates an array of random values between 0 and 1.

Example:

import numpy as np 

 # 2x3 array of random floats
arr_rand = np.random.rand(2, 3) 
print(arr_rand)

Output
[[0.67820861 0.64484802 0.48673431]
 [0.00263043 0.55383721 0.43240166]]
  • Random Integers : If we need random integers, we can use np.random.randint() to create arrays with integer values in a specified range.

Example:

import numpy as np 

 # 3x3 array of random integers from 1 to 9
arr_int = np.random.randint(1, 10, size=(3, 3)) 
print(arr_int)

Output
[[4 6 5]
 [7 4 8]
 [8 5 2]]

Creating Arrays with a Range of Values

Another common method of creating arrays is using a range of values. NumPy provides functions like np.arange() and np.linspace() for this purpose.

  • Using np.arange() : np.arange() creates arrays with values spaced according to a given interval. It’s similar to Python’s built-in range() but returns a NumPy array.

Example:

import numpy as np 

# Array from 0 to 10 with step 2
arr_range = np.arange(0, 10, 2)  
print(arr_range)

Output
[0 2 4 6 8]
  • Using np.linspace(): np.linspace() generates an array with a specified number of evenly spaced values over a specified range.

Example:

import numpy as np 

# 5 values from 0 to 1
arr_linspace = np.linspace(0, 1, 5)  
print(arr_linspace)

Output
[0.   0.25 0.5  0.75 1.  ]

Identity and Diagonal Matrices

NumPy also provides functions for creating identity matrices and diagonal matrices, which are often used in linear algebra.

  • Identity Matrix : np.eye() function creates an identity matrix, a square matrix with ones on the diagonal and zeros elsewhere.

Example:

import numpy as np 

# 3x3 identity matrix
identity_matrix = np.eye(3)  
print(identity_matrix)

Output
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
  • Diagonal Matrix : Use np.diag() to create a diagonal matrix, where the provided array elements form the diagonal.

Example:

import numpy as np

# Diagonal matrix with [1, 2, 3] on the diagonal
diag_matrix = np.diag([1, 2, 3])  
print(diag_matrix)

Output
[[1 0 0]
 [0 2 0]
 [0 0 3]]

Methods for array creation in Numpy

FunctionDescription
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

Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg