Creating NumPy Arrays
Learn different ways to create NumPy arrays
Creating NumPy Arrays
From Python Lists
The most common way to create arrays is from lists.
import numpy as np
my_list = [1, 2, 3, 4, 5]
arr = np.array(my_list)
print(arr)Output: [1 2 3 4 5]
Or directly:
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr)2D Arrays (Matrices)
Create arrays with rows and columns.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)Output:
[[1 2 3]
[4 5 6]]
What this creates: 2 rows, 3 columns. Like a spreadsheet.
Check dimensions:
print("Shape:", matrix.shape)
print("Rows:", matrix.shape[0])
print("Columns:", matrix.shape[1])Output:
Shape: (2, 3)
Rows: 2
Columns: 3
Array of Zeros
Create array filled with zeros.
import numpy as np
zeros = np.zeros(5)
print(zeros)Output: [0. 0. 0. 0. 0.]
2D zeros:
zeros_2d = np.zeros((3, 4))
print(zeros_2d)What this creates: 3 rows, 4 columns, all zeros.
Why use zeros:
- Initialize data before filling
- Create placeholder arrays
- Start calculations at zero
Array of Ones
Create array filled with ones.
import numpy as np
ones = np.ones(4)
print(ones)Output: [1. 1. 1. 1.]
2D ones:
ones_2d = np.ones((2, 3))
print(ones_2d)Use cases:
- Initialize weights in machine learning
- Create masks
- Probability calculations
Array with Range
Create sequences of numbers.
Using arange()
import numpy as np
numbers = np.arange(10)
print(numbers)Output: [0 1 2 3 4 5 6 7 8 9]
With start and stop:
numbers = np.arange(5, 15)
print(numbers)Output: [5 6 7 8 9 10 11 12 13 14]
With step:
evens = np.arange(0, 20, 2)
print(evens)Output: [0 2 4 6 8 10 12 14 16 18]
What step does: Jump by 2 each time instead of 1.
Using linspace()
Create evenly spaced numbers.
import numpy as np
numbers = np.linspace(0, 10, 5)
print(numbers)Output: [0. 2.5 5. 7.5 10.]
What this creates: 5 numbers evenly spaced between 0 and 10.
Difference between arange and linspace:
- arange: You set the step size
- linspace: You set how many numbers you want
Array with Same Value
Fill array with specific value.
import numpy as np
fives = np.full(6, 5)
print(fives)Output: [5 5 5 5 5 5]
2D with same value:
matrix = np.full((3, 3), 7)
print(matrix)Creates: 3x3 matrix filled with 7.
Identity Matrix
Special matrix with 1s on diagonal, 0s elsewhere.
import numpy as np
identity = np.eye(4)
print(identity)Output:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Why identity matrix:
- Linear algebra operations
- Matrix multiplication
- Machine learning transformations
Random Arrays
Create arrays with random numbers.
Random Floats (0 to 1)
import numpy as np
random_floats = np.random.random(5)
print(random_floats)Output: [0.34 0.78 0.12 0.91 0.56] (different each time)
Random Integers
import numpy as np
random_ints = np.random.randint(1, 100, size=10)
print(random_ints)What this creates: 10 random integers between 1 and 99.
Parameters:
- 1: Minimum value (included)
- 100: Maximum value (excluded)
- size: How many numbers
Random Normal Distribution
import numpy as np
normal = np.random.randn(5)
print(normal)What this creates: Random numbers following normal distribution (bell curve).
2D random array:
random_2d = np.random.random((3, 4))
print(random_2d)Creates: 3 rows, 4 columns of random floats.
Specifying Data Type
Control the type of numbers in array.
import numpy as np
integers = np.array([1, 2, 3], dtype=int)
print(integers.dtype)
floats = np.array([1, 2, 3], dtype=float)
print(floats.dtype)
print(floats)Output:
int64
float64
[1. 2. 3.]
Common data types:
- int: Whole numbers
- float: Decimal numbers
- bool: True/False
- str: Text
Converting Lists to Arrays
import numpy as np
python_list = [5, 10, 15, 20]
numpy_array = np.array(python_list)
print("List type:", type(python_list))
print("Array type:", type(numpy_array))Why convert:
- NumPy operations are faster
- Access to NumPy functions
- Better for numerical work
Practice Example
The scenario: Create different arrays for data analysis project.
import numpy as np
student_ids = np.arange(1, 101)
print("Student IDs:", student_ids[:10])
print("Total students:", len(student_ids))
initial_scores = np.zeros(100)
print("Initial scores (first 5):", initial_scores[:5])
attendance = np.ones(100)
print("Attendance initialized:", attendance[:5])
test_scores = np.random.randint(60, 100, size=100)
print("Random test scores (first 10):", test_scores[:10])
grade_weights = np.array([0.3, 0.3, 0.4])
print("Grade weights:", grade_weights)
print("Weights sum:", np.sum(grade_weights))
percentiles = np.linspace(0, 100, 11)
print("Percentiles:", percentiles)
grade_matrix = np.zeros((100, 3))
print("Grade matrix shape:", grade_matrix.shape)
print("(100 students, 3 assignments)")
random_sample = np.random.choice(student_ids, size=10, replace=False)
print("Random sample of 10 students:", random_sample)What this creates:
- Student IDs from 1 to 100
- Initial scores of zero for all students
- Attendance array (all present = 1)
- Random test scores between 60-99
- Grade weights for different assignments
- Percentile markers from 0 to 100
- Empty grade matrix for recording scores
- Random sample of 10 student IDs
Array from Function
Create array using a function.
import numpy as np
def square(x):
return x * x
numbers = np.arange(5)
squared = np.array([square(x) for x in numbers])
print(squared)Or use NumPy's way:
numbers = np.arange(5)
squared = numbers ** 2
print(squared)Output: [0 1 4 9 16]
Combining Arrays
Join multiple arrays together.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
combined = np.concatenate([arr1, arr2])
print(combined)Output: [1 2 3 4 5 6]
Key Points to Remember
Create arrays from lists with np.array([1, 2, 3]). Most common method.
Use np.zeros() and np.ones() to create arrays filled with 0s or 1s. Great for initialization.
np.arange() creates sequences with step size. np.linspace() creates sequences with specific count.
np.random.random() creates random floats, np.random.randint() creates random integers.
Use shape attribute to check dimensions. (rows, columns) for 2D arrays.
Common Mistakes
Mistake 1: Wrong parentheses for 2D
zeros = np.zeros(3, 4) # Error!
zeros = np.zeros((3, 4)) # Correct - note double parenthesesMistake 2: arange doesn't include end
arr = np.arange(1, 10) # Goes from 1 to 9, not 10
arr = np.arange(1, 11) # This gets 1 to 10Mistake 3: linspace includes end
arr = np.linspace(0, 10, 5) # Includes both 0 and 10Mistake 4: Random seed not set
np.random.random(5) # Different every timeFor reproducible results:
np.random.seed(42)
np.random.random(5) # Same results every timeWhat's Next?
You now know how to create NumPy arrays in many ways. Next, you'll learn about array attributes and methods - properties like shape, size, and useful operations you can perform on arrays.