Python for Data & Web
Python NumPy Basics
NumPy is Python's core library for fast numerical computing, built around a powerful array type called the ndarray. It's the foundation almost every data science and machine learning library is built on.
What Is NumPy?
NumPy (Numerical Python) gives you the ndarray, a grid-like data structure for storing numbers that is much faster and more memory-efficient than a plain Python list. Functions and libraries like pandas, scikit-learn, and TensorFlow all rely on NumPy arrays under the hood, so learning it is a key step toward data science.
pip install numpyCreating Arrays
You typically create an array from a Python list using np.array(), or generate one with helper functions like np.zeros(), np.ones(), or np.arange().
import numpy as np
nums = np.array([1, 2, 3, 4, 5])
print(nums)
print(type(nums))
zeros = np.zeros(4)
range_arr = np.arange(0, 10, 2)
print(zeros)
print(range_arr)Vectorised Operations
Unlike a normal list, you can apply an operator directly to an entire array and NumPy applies it element by element. This is called vectorisation, and it removes the need for manual loops, making your code shorter and much faster.
import numpy as np
prices = np.array([100, 200, 300])
discounted = prices * 0.9
print(discounted)
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)Shape and Reshape
Every array has a shape, a tuple describing its dimensions, such as (3,) for a 1D array or (2, 3) for a 2D array with 2 rows and 3 columns. reshape() lets you rearrange the same data into a different shape without changing the values.
import numpy as np
grid = np.array([1, 2, 3, 4, 5, 6])
print(grid.shape)
reshaped = grid.reshape(2, 3)
print(reshaped)
print(reshaped.shape)Import NumPy with the common alias np — almost every tutorial, function, and Stack Overflow answer you find will use that convention.
| Function | What it does |
|---|---|
| np.array() | Create an array from a list |
| np.zeros(n) | Array of n zeros |
| np.arange(start, stop, step) | Array like Python range() |
| .shape | Tuple of array dimensions |
| .reshape() | Change dimensions, same data |
NumPy arrays must hold a single data type (like all integers or all floats), which is part of why they are faster than mixed-type Python lists.
Frequently Asked Questions
Is NumPy part of standard Python?+
No, NumPy is a third-party library. Install it with pip install numpy before importing it in your code.
How is a NumPy array different from a Python list?+
A NumPy array stores elements of one data type in a compact block of memory and supports vectorised math, so operations run much faster than looping over a list.
Do I need to know NumPy before learning pandas?+
It helps a lot. Pandas is built on top of NumPy, so understanding arrays makes concepts like DataFrame columns and vectorised operations click faster.
