Create Array in NumPy: A Beginner Introduction

In this tutorial, we will introduce some methods to create array in NumPy.

1. The most common way is to create an array using a python list.

import numpy as np 
 
array = np.array([[1, 2], [3, 4]])

2. We also can use some numpy methods to create numpy array.

There are some numpy methods that allow us to create numpy array. Here is a list:

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

For example, we can create a zero array.

a = np.zeros([2, 2], dtype = int)
print(a)

NumPy array a will be:

[[0 0]

 [0 0]]