Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How to Create NumPy Arrays: A Comprehensive Guide

5 min read

NumPy is one of the most popular packages in the Python ecosystem. NumPy adds support to large multidimensional arrays and matrices with great efficiency.

Numpy arrays are a lot faster than traditional python lists because they are stored in continuous memory that allows faster processing and accessing thus making large data processing a lot faster and convenient.

In this tutorial, we will learn how to create NumPy arrays.

Prerequisite

You must have Python3+ installed in your system, if that's not the case following articles can help you.

Second, you must have the latest version of NumPy installed in your system. Use the following command to install NumPy.

pip install numpy

How to create NumPy arrays

There are multiple ways you can create an array in Numpy, let's go over the most common ones one by one.

Creating NumPy array with arrange function

NumPy comes with a built-in method arrange() that's quite similar to the range() function in Python.

import numpy as np
a = np.arange(11) # creates a range from 0 to 10
print(a)
print(a.shape)

Output

[ 0  1  2  3  4  5  6  7  8  9 10]
(11,)

First, we import the NumPy package as np then we invoked the arrange() method with a value. Since we passed only one value it will create a rank 1 array or one-dimensional array of 11 elements.

Noticed how indexing starts from 0? Therefore we don't have the number 11 on the list.

The shape property returns the shape of the array which is a one-dimensional array with 11 elements or you can think of it as an 11*1 matrix.

Note - Arrays and Matrix are often used interchangeably. It's very crucial to know the difference between the two in terms of NumPy.

Numpy matrices are strictly 2-dimensional, while NumPy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

As per the official documents, it's not advisable to use matrix class since it will be removed in the future - https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

 

You can play around with the arrange() function by passing negatives values such as.

import numpy as np
a = np.arange(-5, -1)
print(a)

Output

[-5 -4 -3 -2]

As you can observe the default step between the elements is 1, this can also be configured.

import numpy as np
a = np.arange(0,11,2) # creates a range from 0 to 10, step 2
print(a)
Output
[ 0  2  4  6  8 10]

Similar to python's range() function we can pass attributes such as start, stop and step to the arrange() function.

arange(start, stop, step)

This step function can be used to count backward as well.

import numpy as np
a = np.arange(5, 1, -1)
print(a)

Output

[5 4 3 2]

Creating NumPy array with zeros function

import numpy as np

a = np.zeros(5) # create an array with all 0s

print(a) # [ 0. 0. 0. 0. 0.]print(a.shape)
Output
[0. 0. 0. 0. 0.]
(5,)

Now let's create some two-dimensional arrays with the zeros() method.

import numpy as np
a = np.zeros((2,3)) # array of rank 2 with all 0s; 2 rows and 3 columns
print(a.shape)
print(a)
Output
(2, 3)
[[0. 0. 0.] [0. 0. 0.]]

The zeros() method takes shape as the first argument

zeros(shape)

This shape could be an int for a 1D array and a tuple of ints for an N-D array. Thus we passed a tuple as an argument to create a 2D array where the former is the number of rows and the latter is the number of columns.

np.zeros((2,3)) # array of rank 2 with all 0s; 2 rows and 3

Let's go ahead and create a 3D array with zeros.

import numpy as np

a = np.zeros((3,2,3)) # array of rank 3 with all 0s; 2 rows and 3
print(a.shape)
print(a)

Output

(3, 2, 3)
[[[0. 0. 0.]  [0. 0. 0.]] [[0. 0. 0.]  [0. 0. 0.]] [[0. 0. 0.]  [0. 0. 0.]]]

To create a 3D array and above we need to pass a tuple with 3 elements to the zeros() method. Here the first element is the rank of the array and the latter are the number of rows and column respectively.

Other than shape zeros take two more arguments.

numpy.zeros(shape, dtype=float, order='C')
  • Here dtype is the datatype of the elements which by default is float.
  • The order parameter determines how the data is stored in memory. C: C-style of storing multi-dimensional data in row-major memory. F: Fortran style of storing multi-dimensional data in column-major in memory.

So in case you want to create a zeros array with only integers you would wanna do something like this.

import numpy as np
a = np.zeros((2,3), int) # array of rank 2 with all 0s; 2 rows and 3 with integer values
print(a)

Output

[[0 0 0] [0 0 0]]

Creating Numpy arrays with the full function

Instead of 0's let's say you want to creates arrays full of a different number for instance let the number be 6, then you could use the full() function of NumPy.

import numpy as np
a = np.full((2,3), 6) # array of rank 2 with all 6s
print(a)

Output

[[6 6 6] [6 6 6]]

The function is quite similar to the zeros() function which we saw earlier this one just takes an additional argument fill_value.

np.full(shape, fill_value, dtype = None, order = 'C')

Creating NumPy arrays with eye function

Sometimes, you need to create an array that mirrors an identity matrix. You can do so using the eye() function.

For those who don't remember what an identity matrix is - A square matrix in which all the elements of the principal diagonal are ones and all other elements are zeros.

a = np.eye(4) # 4x4 identity matrix

Output

[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]

Creating NumPy array of random numbers

import numpy as np
a = np.random.random((2,4)) # rank 2 array (2 rows 4 columns) with random values in the half-open interval [0.0, 1.0]
print(a)

Output

[[0.60750379 0.86313917 0.06771915 0.38928062] [0.03435306 0.45732639 0.50627336 0.69863683]]

Similarly, you can create a 3D array using the random() function.

a = np.random.random((3,2,4))

Output

[[[0.98981043 0.87668365 0.60244216 0.18769144]  [0.95372264 0.92507173 0.74217822 0.39551042]] [[0.03540292 0.43823864 0.28823769 0.71393248]  [0.84661176 0.58682121 0.33108038 0.91641688]] [[0.83330768 0.40824907 0.01822309 0.2082025 ]  [0.77093124 0.72571395 0.81175314 0.08715285]]]

Notice how all the values are within the range of (0,1)?

What if you want to create a uniform matrix within a different range?

For example a 2D array within the range of 1 to 10 having 2 rows and 3 columns. You can do so using the random.uniform() function.

import numpy as np
a = np.random.uniform(low=1, high=10, size=(2,3))
print(a)

Output

[[6.14970466 9.91562178 6.58209242] [4.83473852 3.28020197 3.06821119]]

Creating NumPy array from a Python list

Of course, python allows the creation of NumPy array from a regular python list.

import numpy as np

some_list = [1,2,3,4,5]
arr = np.array(some_list)print(arr)

Output

[1 2 3 4 5]


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read