Learn NumPy · 2/15

Forging Arrays: Creation and Initialization

6 min read

Forging Arrays: Creation and Initialization 🔩

Welcome to the NumPy forge! Here, we'll learn how to craft the fundamental building block of NumPy: the array. Think of this as learning to create your raw materials before you can build something magnificent. We'll cover the most common and practical ways to create arrays that you'll use time and again in your data science and machine learning adventures.

First things first, let's make sure you have NumPy ready to go. If you have Python and pip, you can install it with a simple command in your terminal:

bash
pip install numpy

Now, let's start forging!

1. From Lists to Arrays: np.array()

The Problem: You have some data neatly organized in a Python list, but Python lists are like carrying your tools one by one. They're flexible but not very efficient for heavy-duty numerical tasks. For that, you need a proper toolbox.

The Solution: The np.array() function is your go-to tool for converting Python lists (and other sequence-like objects) into powerful NumPy arrays. It takes a list as input and forges it into an ndarray, the core data structure in NumPy.

Imagine you're a city planner, and you have the populations of several districts in a list.

python
import numpy as np

# A standard Python list
city_populations_list = [120000, 250000, 98000, 310000]

# Let's forge it into a NumPy array!
city_populations_array = np.array(city_populations_list)

print(city_populations_array)
print(type(city_populations_array))

Output:

actionscript
[120000 250000  98000 310000]
<class 'numpy.ndarray'>

Notice the difference in the output? No commas! That's one of the visual cues that you're now dealing with a NumPy array. More importantly, under the hood, NumPy has organized this data in a way that allows for lightning-fast mathematical operations.

You can also create multi-dimensional arrays by passing in a list of lists. This is incredibly useful for representing things like matrices or images.

python
# A list of lists representing a 2x3 grid of data
grid_data = [[1, 2, 3], [4, 5, 6]]

# Forging a 2D array
grid_array = np.array(grid_data)

print(grid_array)

Output:

lua
[[1 2 3]
 [4 5 6]]

A funny thing about np.array() is that it's a bit like a meticulous chef. It inspects all the ingredients (the elements in your list) and decides on the best data type (dtype) for the whole dish. If you give it all integers, you'll get an integer array. Throw in one floating-point number, and it will wisely make the whole array of floats to avoid losing precision.

2. Built-in Creators: zeros(), ones(), and full()

The Problem: Sometimes, you need to create an array of a specific size, but you don't have the data for it yet. You need a placeholder, a blank canvas to paint your data on later.

The Solution: NumPy provides handy functions to create arrays filled with specific values. These are incredibly useful for initializing arrays before you populate them with results from a calculation.

np.zeros()

This function creates an array of a given shape filled entirely with zeros. It's like reserving a plot of land before you start building.

python
# Create a 1D array of 5 zeros
zero_vector = np.zeros(5)
print(zero_vector)

# Create a 3x4 2D array (matrix) of zeros
zero_matrix = np.zeros((3, 4))
print(zero_matrix)

Output:

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

By default, np.zeros() creates an array of floating-point numbers. If you need integers, you can specify the data type.

python
zero_matrix_int = np.zeros((3, 4), dtype=int)
print(zero_matrix_int)

Output:

lua
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

np.ones()

Similar to zeros(), np.ones() creates an array filled with ones. This is useful in various mathematical computations, like creating a base for multiplication.

python
# Create a 2x3 array of ones
one_matrix = np.ones((2, 3))
print(one_matrix)

Output:

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

np.full()

What if you want an array filled with a number that isn't 0 or 1? np.full() is your hero! It creates an array of a given shape filled with a value you specify.

python
# Create a 2x2 array filled with the number 7
sevens_matrix = np.full((2, 2), 7)
print(sevens_matrix)

Output:

lua
[[7 7]
 [7 7]]

A fun fact: Under the hood, creating an array with these functions is more efficient than creating a Python list and then converting it, especially for large arrays.

3. Generating Sequences: arange() and linspace()

The Problem: You often need to create arrays with a sequence of numbers, like a range of time steps for a simulation or a set of values to plot a function.

The Solution: NumPy offers powerful functions to generate numerical ranges.

np.arange()

np.arange() is NumPy's version of the Python range() function, but it returns a NumPy array. It generates values within a given interval.

python
# An array from 0 up to (but not including) 10
sequence = np.arange(10)
print(sequence)

# An array from 5 up to (but not including) 10
sequence_start_stop = np.arange(5, 10)
print(sequence_start_stop)

# An array from 0 up to 10, with a step of 2
sequence_with_step = np.arange(0, 11, 2)
print(sequence_with_step)

Output:

tap
[0 1 2 3 4 5 6 7 8 9]
[5 6 7 8 9]
[ 0  2  4  6  8 10]

A word of caution from the wise old data wizards: be careful when using np.arange() with floating-point steps. Due to the way computers handle floating-point numbers, you might get some unexpected results. For those cases, it's often better to use np.linspace().

np.linspace()

np.linspace() is fantastic when you care more about the number of points in your sequence rather than the step size. It returns evenly spaced numbers over a specified interval.

Imagine you're an audio engineer and you need to sample a sound wave at exactly 5 points between 0 and 1 second.

python
# Generate 5 evenly spaced points from 0 to 1 (inclusive)
time_samples = np.linspace(0, 1, 5)
print(time_samples)

Output:

accesslog
[0.   0.25 0.5  0.75 1.  ]

By default, linspace includes the endpoint. You can change this behavior if you need to.

python
# Generate 5 evenly spaced points from 0 to 1 (exclusive of the endpoint)
time_samples_exclusive = np.linspace(0, 1, 5, endpoint=False)
print(time_samples_exclusive)

Output:

dns
[0.  0.2 0.4 0.6 0.8]

4. Creating Identity Matrices: eye()

The Problem: In linear algebra, the identity matrix is a fundamental tool. It's the matrix equivalent of the number 1. You'll often need to create one for various calculations.

The Solution: NumPy's np.eye() function is the perfect tool for this job. It creates a 2D array with ones on the diagonal and zeros elsewhere.

python
# Create a 3x3 identity matrix
identity_matrix = np.eye(3)
print(identity_matrix)

Output:

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

You can also create non-square matrices and shift the diagonal up or down.

python
# Create a 3x5 matrix with the diagonal of ones
rectangular_eye = np.eye(3, 5)
print(rectangular_eye)

# Create a 3x3 matrix with the diagonal shifted up by 1
shifted_eye = np.eye(3, k=1)
print(shifted_eye)

Output:

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

And there you have it! You've learned the essential techniques for forging NumPy arrays. With these tools, you're now ready to create the foundational elements for your future data explorations.

References for Extra Reading

Challenge

You are tasked with setting up the initial data structures for a new e-commerce analytics system using NumPy. Your goal is to create several specific arrays that will serve as placeholders and initial data.

Assign the resulting NumPy arrays to the specified variable names.

  1. Create a 1D NumPy array named product_prices from the given Python list prices_list.
  2. Initialize a 2D user feature matrix named user_features. This matrix should have 10 rows and 5 columns, and all its elements should be floating-point ones.
  3. Generate a 2D array named sales_data_placeholder with a shape of (100, 4), filled entirely with the integer value -1 to represent unrecorded sales.
  4. Create a 1D array named user_ids containing a sequence of integers from 100 up to (but not including) 200.
  5. Generate an array named discount_levels that contains exactly 10 evenly spaced values starting from 0.05 and ending at 0.50 (inclusive).
  6. Finally, create a 5x5 identity matrix named transformation_matrix for use in future linear algebra calculations.

Expected result

Your code should correctly define six variables using the appropriate NumPy functions. The content of each variable should be as follows:

  • product_prices: A 1D array created from the prices_list.
    angelscript
    [ 19.99  25.5   9.95 150.    75.25]
  • user_features: A 10x5 2D array where every element is 1..
    inform7
    [[1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]
     [1. 1. 1. 1. 1.]]
  • sales_data_placeholder: A 100x4 2D array where every element is the integer -1.
  • user_ids: A 1D array containing integers from 100 to 199.
  • discount_levels: A 1D array with 10 evenly spaced numbers from 0.05 to 0.50.
    dns
    [0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45 0.5 ]
  • transformation_matrix: A 5x5 identity matrix.
    inform7
    [[1. 0. 0. 0. 0.]
     [0. 1. 0. 0. 0.]
     [0. 0. 1. 0. 0.]
     [0. 0. 0. 1. 0.]
     [0. 0. 0. 0. 1.]]
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.