Problem Formulation and Solution Overview
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.
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 (
) by using weight values for the first five (5) elements in the Periodic Table. The results save to np.array()
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 (
) by using weight values for the first six (6) elements in the Periodic Table.np.array()
[[ 1.008 6.94 22.99 ] |
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])] |
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
and are output to the terminal.zero_dims
[[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,
is called and passed an array shape of three (3) columns and two (2) rows (np.ones()
3,2
) as an argument. The results save to
and are output to the terminal.one_dims
[[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,
is called and passed an array shape of two (2) columns and four (4) rows (np.full()
2,4
) as an argument. The results save to
and are output to the terminal.fill_dims
[[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,
is called and passed a dimension shape of two (2) columns and two (2) rows (np.empty()
2,2
) as an argument. The results save to
and are output to the terminal.empty_dims
[[6.23042070e-307 1.42417221e-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,
is called and passed a stop position of five (5) as an argument. The results save to np.empty()
and are output to the terminal.range_dims
[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] |
π Recommended Tutorial: How to Convert Pandas DataFrame/Series to NumPy Array?
Summary
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!)