How To Initialize A NumPy Array

There are plenty of ways to initialize a NumPy array, depending on the desired values you want to get in the returned array. Check out these common approaches and their examples.

Initialize A NumPy Array

NumPy supports multiple methods for creating arrays:

  • Create a NumPy array that has a predefined value pattern, such as only zero values or values within a range.
  • Create a NumPy array from a Python data structure, such as a tuple or a list.
  • Create a NumPy array from data stored in your filesystems.
  • Create a NumPy array by copying or joining existing arrays.

Use Predefined Patterns

NumPy provides a whole host of array creation routines, many of which work in the same way as its built-in Python counterparts.

For instance, numpy.arange() can return values evenly spaced within an interval. You can give it start, stop, and step values. When the start and step arguments are omitted, numpy.arange() sets them to 0 and 1 by default.

This is how you can create a NumPy array with integer values between 2 and 9:

>>> import numpy as np
>>> np.arange(2, 9)
array([2, 3, 4, 5, 6, 7, 8])

If you want to fill the returned array with zeros or ones, use numpy.zeros() and numpy.ones(). These functions get the shape of the returned array from an integer tuple:

>>> np.zeros((2, 3))
array([[0., 0., 0.],
       [0., 0., 0.]])
>>> np.ones(4)
array([1., 1., 1., 1.])

Another function you can use to create 2D arrays is numpy.eye(). It will set the elements on the diagonal to 1 and the rest of the array 0.

>>> np.eye(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

From A Python Data Structure

You can use sequences like tuples and lists to create NumPy arrays with numpy.array(). This function will create a 1D array from one-dimensional and higher-dimensional arrays from a nested list.

In this example, we create two Python lists and use numpy.array() to initialize two arrays from them:

import numpy as np
list1 = [1, 2, 3, 4]
list2 = [[1, 2], [3, 4]]
ndarray1 = np.array(list1)
ndarray2 = np.array(list2)
print(ndarray1)
print(ndarray2)

Output

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

Note: follow instructions from this guide if you can’t find the array() function.

From Data Stored In Disks

If you have data stored in CSV or TSV files, you can use numpy.loadtxt() and numpy.genfromtxt() to create NumPy arrays from it.

Let’s say you have a CSV call data.csv like this:

1, 2, 3

4, 5, 6

Here is how you can import it with numpy.loadtxt():

>>> np.loadtxt('data.csv', delimiter = ',')
array([[1., 2., 3.],
       [4., 5., 6.]])

Join Or Mutate Existing Arrays

Functions like numpy.vstack(), numpy.hstack(), and numpy.block() can help you join multiple existing arrays into a single NumPy array.

In particular, the numpy.block() can arrange multiple arrays into a layout. In this example, we first create 4 2×2 arrays, then we create a 4×4 array from them by stacking them with a predefined layout:

>>> a = np.zeros((2, 2))
>>> b = np.array([[1, 2], [3, 4]])
>>> c = np.ones((2, 2))
>>> d = np.array([[5, 6], [7, 8]])
>>> np.block([[a, b], [c, d]])
array([[0., 0., 1., 2.],
       [0., 0., 3., 4.],
       [1., 1., 5., 6.],
       [1., 1., 7., 8.]])

Summary

Depending on your needs, you can initialize a NumPy array in different ways. This library comes with a huge number of functions for array creation. Learn to use them so you can pick the best choice in each situation.

Leave a Reply

Your email address will not be published. Required fields are marked *