🏗️ NumPy Array Creation: Building Your Data Kingdom
Imagine you’re a master builder. Before you can create amazing castles, you need to know how to make the perfect bricks. In NumPy, arrays are your bricks—and today, you’ll learn every magical way to create them!
🎯 The Big Picture
Think of NumPy arrays like LEGO boxes. You can:
- Fill a box with specific pieces you already have
- Get a box pre-filled with the same piece everywhere
- Copy the shape of another box
- Get pieces numbered 1, 2, 3… in order
- Create special patterns (like diagonal lines)
- Build grids (like graph paper)
- Use a magic formula to decide what goes where
Let’s explore each way!
📦 Creating Arrays from Sequences
What’s a Sequence?
A sequence is just a list of things in order—like beads on a necklace!
The np.array() Magic Wand
import numpy as np
# From a simple list
my_list = [1, 2, 3, 4, 5]
arr = np.array(my_list)
# Result: array([1, 2, 3, 4, 5])
Think of it like: You have toys scattered on the floor. np.array() puts them neatly in a special box.
2D Arrays (Tables!)
# A grid of numbers
table = np.array([
[1, 2, 3],
[4, 5, 6]
])
# 2 rows, 3 columns!
Real Life: Like a seating chart—rows and columns of seats.
From Tuples Too!
my_tuple = (10, 20, 30)
arr = np.array(my_tuple)
# Works the same way!
🔵 Constant Value Arrays
What If You Need the Same Thing Everywhere?
Sometimes you need a box filled with all the same piece. NumPy has special tools for this!
np.zeros() — Fill with Zeros
# 5 zeros in a row
zeros = np.zeros(5)
# array([0., 0., 0., 0., 0.])
# 3 rows, 4 columns of zeros
zero_grid = np.zeros((3, 4))
Think of it like: A brand new notebook—all blank pages!
np.ones() — Fill with Ones
# 4 ones
ones = np.ones(4)
# array([1., 1., 1., 1.])
# 2x3 grid of ones
ones_grid = np.ones((2, 3))
Think of it like: Every light switch turned ON.
np.full() — Fill with ANY Value
# 5 sevens
sevens = np.full(5, 7)
# array([7, 7, 7, 7, 7])
# 3x3 grid of 42s
grid = np.full((3, 3), 42)
Think of it like: Painting every room the same color!
🪞 Arrays Matching Shape
Copying Another Array’s Shape
Sometimes you want a new array that’s the same size as one you already have.
np.zeros_like() — Same Shape, All Zeros
original = np.array([[1, 2], [3, 4]])
# Make zeros with same shape
empty_copy = np.zeros_like(original)
# array([[0, 0], [0, 0]])
np.ones_like() — Same Shape, All Ones
ones_copy = np.ones_like(original)
# array([[1, 1], [1, 1]])
np.full_like() — Same Shape, Your Value
fives = np.full_like(original, 5)
# array([[5, 5], [5, 5]])
Think of it like: Tracing the outline of a cookie cutter to make the same shape!
🔢 Sequential and Spaced Arrays
Arrays That Count
What if you want numbers that go 1, 2, 3, 4…?
np.arange() — Count Like a Pro
# 0 to 4 (stop before 5!)
count = np.arange(5)
# array([0, 1, 2, 3, 4])
# 2 to 9
range_arr = np.arange(2, 10)
# array([2, 3, 4, 5, 6, 7, 8, 9])
# Count by 2s: 0, 2, 4, 6, 8
by_twos = np.arange(0, 10, 2)
Think of it like: A number line you can customize!
np.linspace() — Even Spacing
# 5 numbers from 0 to 10, evenly spaced
even = np.linspace(0, 10, 5)
# array([0., 2.5, 5., 7.5, 10.])
# 4 numbers from 1 to 4
spaced = np.linspace(1, 4, 4)
# array([1., 2., 3., 4.])
Think of it like: Placing fence posts with equal gaps between them.
Key Difference
arange |
linspace |
|---|---|
| You set the step size | You set how many numbers |
| Endpoint not included | Endpoint IS included |
⬛ Diagonal and Identity Matrices
What’s an Identity Matrix?
It’s a special square grid with 1s on the diagonal and 0s everywhere else. Like the “do nothing” button in math!
np.eye() — The Eye-dentity
# 3x3 identity matrix
I = np.eye(3)
# array([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
# 4x4 identity
I4 = np.eye(4)
Think of it like: A mirror that shows the same number back when you multiply!
np.identity() — Always Square
# Same result, but always square
I = np.identity(3)
np.diag() — Custom Diagonals
# Create from diagonal values
diag_arr = np.diag([1, 2, 3])
# array([[1, 0, 0],
# [0, 2, 0],
# [0, 0, 3]])
# Extract diagonal from matrix
matrix = np.array([[1, 2], [3, 4]])
diagonal = np.diag(matrix)
# array([1, 4])
Think of it like: Drawing a line from corner to corner!
🗺️ Creating Coordinate Grids
What’s a Coordinate Grid?
Think of graph paper. Every spot has an (x, y) address. NumPy helps you make these!
np.meshgrid() — Graph Paper Maker
x = np.array([1, 2, 3])
y = np.array([10, 20])
X, Y = np.meshgrid(x, y)
# X = array([[1, 2, 3],
# [1, 2, 3]])
# Y = array([[10, 10, 10],
# [20, 20, 20]])
Think of it like: Making a map where you can find any point!
Real Use: Plotting 3D Surfaces
# For a 3D graph
x = np.linspace(-5, 5, 10)
y = np.linspace(-5, 5, 10)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2 # A bowl shape!
np.mgrid and np.ogrid — Quick Grids
# Dense grid (like meshgrid)
X, Y = np.mgrid[0:3, 0:4]
# Sparse grid (memory saver)
x, y = np.ogrid[0:3, 0:4]
🧙‍♂️ Using np.fromfunction
The Magic Formula
What if you want each cell’s value to depend on WHERE it is?
np.fromfunction() — Position-Based Values
# Function takes (row, column) position
def my_func(i, j):
return i + j
arr = np.fromfunction(my_func, (3, 3))
# array([[0., 1., 2.],
# [1., 2., 3.],
# [2., 3., 4.]])
How it works:
- Position (0,0) → 0+0 = 0
- Position (0,1) → 0+1 = 1
- Position (1,1) → 1+1 = 2
More Examples
# Multiplication table!
def mult(i, j):
return (i + 1) * (j + 1)
table = np.fromfunction(mult, (5, 5))
# 1 2 3 4 5
# 2 4 6 8 10
# 3 6 9 12 15
# ...
# Distance from corner
def distance(i, j):
return np.sqrt(i**2 + j**2)
dist = np.fromfunction(distance, (4, 4))
Think of it like: A robot that visits every cell and calculates its value based on the address!
🎯 Quick Reference Flow
graph LR A[Need an Array?] --> B{Have data?} B -->|Yes| C[np.array] B -->|No| D{Same value?} D -->|Zeros| E[np.zeros] D -->|Ones| F[np.ones] D -->|Custom| G[np.full] A --> H{Copy shape?} H -->|Yes| I[zeros_like<br>ones_like<br>full_like] A --> J{Sequence?} J -->|Step size| K[np.arange] J -->|Count| L[np.linspace] A --> M{Special?} M -->|Diagonal| N[np.eye/diag] M -->|Grid| O[np.meshgrid] M -->|Formula| P[np.fromfunction]
🏆 You Did It!
You now know 7 powerful ways to create NumPy arrays:
- ✅ From sequences — Turn lists into arrays
- ✅ Constant values — Fill with zeros, ones, or any number
- ✅ Matching shapes — Copy another array’s size
- ✅ Sequential arrays — Count and space numbers
- ✅ Diagonals — Create identity and diagonal matrices
- ✅ Coordinate grids — Build graph paper for math
- ✅ From functions — Calculate values by position
You’re ready to build anything! 🚀
“Every expert was once a beginner. Now you’ve got the tools—go create something amazing!”