How to Initialize a NumPy Array? 6 Easy Ways

5/5 - (1 vote)

Problem Formulation and Solution Overview

In this article, you’ll learn how to initialize a NumPy array in Python using six (6) of the most commonly used methods.

Background: NumPy is Python’s impressive array-based data structure library used to perform intense mathematical calculations popularized by the Machine Learning and Data Science community.

Let’s start by creating and initializing a NumPy array.

πŸ’¬ Question: How would we initialize a NumPy array?

We can accomplish this task by one of the following options:


Preparation

Before moving forward, please ensure the NumPy library is installed on the computer. Click here if you require instructions.

Add the following code to the top of each script. This snippet will allow the code in this article to run error-free.

import numpy as np 

After importing the NumPy library, we can reference this library by calling the shortcode (np) shown above.


Method 1: Use NumPy Array()

One way to initialize a NumPy array is to enter exact values in a List format. Then pass this List as an argument to np.array().

Example: 1-Dimensional Array

one_dim = np.array([1.008, 6.94, 22.990, 39.098, 85.468])
print(one_dim)

This example initializes a 1D NumPy array (np.array()) by using weight values for the first five (5) elements in the Periodic Table. The results save to one_dim and are output to the terminal.

[ 1.008 6.94 22.99 39.098 85.468]

Example: 2-Dimensional Array or Higher

two_dim = np.array([[1.008, 6.94, 22.990], [39.098, 85.468, 132.91]])
print(two_dim)

This example initializes a 2D NumPy array (np.array()) by using weight values for the first six (6) elements in the Periodic Table.

[[ 1.008 6.94 22.99 ]
[ 39.098 85.468 132.91 ]]

For 2D NumPy arrays or higher, an error will occur if the dimensions do not contain an equal number of elements.

Example: Correct Dimension Issue

This issue can be corrected by wrapping each dimension in a List and assigning the dtype to an object (dtype=object).

dif_dim = np.array([list([1.008, 6.94, 22.99]), list([39.098, 85.468])], dtype=object)
print(dif_dim)
[list([1.008, 6.94, 22.99]) list([39.098, 85.468])]
NumPy Tutorial - Everything You Need to Know to Get Started

Method 2: Use NumPy Zeroes()

Another way to initialize a NumPy array is to call np.zeros(). This creates a new array with a defined shape (n,n) filled with zeroes.

zero_dims = np.zeros((3,2))
print(zero_dims)

Above, np.zeros() is called and passed an array shape of three (3) columns and two (2) rows (3,2) as an argument. The results save to zero_dims and are output to the terminal.

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

πŸ’‘Note: The shape of the new array can be a single integer (2) or a Tuple of integers (3,2).


Method 3: Use NumPy ones()

Similar to Method 2, this initializes a NumPy array and calls np.ones(). This creates a new array with a defined shape (n,n) filled with ones.

one_dims = np.ones((3,2))
print(one_dims)

Above, np.ones() is called and passed an array shape of three (3) columns and two (2) rows (3,2) as an argument. The results save to one_dims and are output to the terminal.

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

Method 4: Use NumPy Full()

What if you want to assign the elements of a NumPy array a specific value? Then, np.full() is a good option. You can enter a value and populate the array with the same.

fill_dims = np.full((2,4), 1.2)
print(fill_dims)

Above, np.full() is called and passed an array shape of two (2) columns and four (4) rows (2,4) as an argument. The results save to fill_dims and are output to the terminal.

[[1.2 1.2 1.2 1.2]
[1.2 1.2 1.2 1.2]]

Method 5: Use NumPy empty()

If you are unsure what values to use to initialize a NumPy array, call np.empty(). This function is passed an array shape and returns random floats.

empty_dims = np.empty((2, 2))
print(empty_dims)

Above, np.empty() is called and passed a dimension shape of two (2) columns and two (2) rows (2,2) as an argument. The results save to empty_dims and are output to the terminal.

[[6.23042070e-307 1.42417221e-306]
[1.37961641e-306 1.11261027e-306]]

πŸ’‘Note: As you can see from the output, empty does not mean empty as it generates and returns random float values.

Method 6: Use NumPy arange()

To populate a 1D NumPy array with uniformly spaced values, call np.arange(). This function is passed an end position (n-1) and starts at zero (0).

range_dims = np.arange(5)
print(range_dims)

Above, np.empty() is called and passed a stop position of five (5) as an argument. The results save to range_dims and are output to the terminal.

[0 1 2 3 4]

Bonus

For our bonus, one (1) column from a CSV file is read into a DataFrame. This column is then converted into a 1D NumPy array and output to the terminal.

To follow along, click here to download the Finxter CSV file and move it into the current working directory before moving forward.

import numpy as np 
import pandas as pd 

df = pd.read_csv('finxters.csv', usecols=['Solved'])
df = df.to_numpy()
print(df)

Above imports the pandas library to allow access to DataFrames. Then the finxters.csv file is opened, and one (1) column, Solved, is accessed. The results save to df.

Next the contents of df are converted to a NumPy array using df.to_numpy(). The results are output to the terminal.

Snippet

[[1915]
[1001]
[ 15]
[1415]
[1950
...]

Summary

These methods of initializing a NumPy Array should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor

❓ Question: Why do programmers always mix up Halloween and Christmas?
❗ Answer: Because Oct 31 equals Dec 25.

(If you didn’t get this, read our articles on the oct() and int() Python built-in functions!)