Thuta Learning
BasicData & Databasesintermediate

Creating Arrays

Relax. We'll talk through this in plain words — no textbook voice.

Before you can crunch data in NumPy, you first need to build an array. There are several ways to create one, and the most common are np.array(), np.zeros(), np.ones(), np.arange(), np.linspace(). Which function to use depends on how you want your data to start out.

python
import numpy as np

# Create an array from an existing list
prices = np.array([1200, 1500, 1800, 2100])
print("Prices:", prices)

# Create a 2 rows x 3 columns array filled with zeros
empty_table = np.zeros((2, 3))
print("
Empty table:
", empty_table)

# Create values from 0 to 8, step by 2
steps = np.arange(0, 10, 2)
print("
Steps:", steps)

# Create 5 evenly spaced values between 0 and 1
percent = np.linspace(0, 1, 5)
print("
Percent points:", percent)

np.array() turns an existing list into an array. np.zeros((2, 3)) builds a table of zeros with 2 rows and 3 columns. np.arange(0, 10, 2) — notice that the stop value, 10, is not included. np.linspace(0, 1, 5) splits the range between 0 and 1 into 5 evenly spaced points.

You should see
Prices: [1200 1500 1800 2100] Empty table: [[0. 0. 0.] [0. 0. 0.]] Steps: [0 2 4 6 8] Percent points: [0. 0.25 0.5 0.75 1. ]

Info

shape needs to be written as a tuple in the form (rows, columns). np.zeros(2, 3) won't give you what you expect.

Easy traps

  • np.arange() doesn't include the stop number. If you want 10 included when going from 0 to 10, write np.arange(0, 11).

Exercise

In data analysis projects, you'll often convert numbers from a CSV or database into an array to run calculations on. Setting up an empty result array ahead of time is handy for storing calculation results later on.

python
import numpy as np

# Monthly sales for 6 months
sales = np.array([120, 135, 150, 160, 155, 180])

# Prepare an empty result array for future calculations
bonus_points = np.zeros(sales.shape)

print("Sales:", sales)
print("Bonus placeholder:", bonus_points)

You'll know it worked when: Sales: [120 135 150 160 155 180] Bonus placeholder: [0. 0. 0. 0. 0. 0.]

Creating Arrays | Thuta Learning