What is NumPy?#
NumPy (Numerical Python) is the library for fast maths on large arrays of numbers. pandas is built on top of NumPy, so understanding arrays makes pandas easier.
import numpy as np # the standard alias
On your computer, install with pip install numpy pandas matplotlib (Anaconda and Google Colab already include them). In this site's editor they load automatically the first time - it can take 10-20 seconds.
Lists vs arrays#
| Python list | NumPy array |
|---|---|
| any mix of types | one type (all numbers) |
* repeats, + joins |
element-wise maths |
| needs loops for maths | vectorised - no loops |
| slower | 10-100× faster on large data |
NumPy array एक ऐसी list है जिसमें सिर्फ numbers होते हैं, और उस पर पूरा गणित एक साथ होता है - loop लिखने की ज़रूरत नहीं।
जैसे 10 लाख products के दाम पर GST जोड़ना: list में loop चलाना पड़ेगा (धीमा), जबकि array में बस prices * 1.18 लिखो - एक line, और बहुत तेज़। इसे vectorisation कहते हैं। pandas अंदर से इसी NumPy पर चलता है।
Creating arrays#
Shape, dimensions and dtype#
Indexing and slicing#
Works like lists, with [row, column] for 2D:
Boolean filtering (masks)#
The most important NumPy idea for analysts - and it works exactly the same in pandas:
Use &, | and ~ (not and, or, not) to combine array conditions, and wrap each condition in brackets: (a > 5) & (a < 10).
Aggregations and axis#
axis समझना ज़रूरी है:
axis=0→ ऊपर से नीचे (rows को मिलाकर) - हर column का एक जवाब (जैसे हर quarter का total)axis=1→ बाएँ से दाएँ (columns को मिलाकर) - हर row का एक जवाब (जैसे हर store का total)
pandas में भी axis का मतलब बिल्कुल यही है।
Broadcasting#
NumPy automatically stretches smaller arrays to match bigger ones:
Useful functions#
| Function | Use |
|---|---|
np.where(cond, a, b) |
if-else on arrays: np.where(profit < 0, "Loss", "Profit") |
np.round(a, 2) |
rounding |
np.unique(a, return_counts=True) |
unique values and counts |
np.percentile(a, 90) |
percentiles |
np.cumsum(a) |
running total |
np.isnan(a) |
find missing values (np.nan) |
Summary#
- NumPy arrays hold numbers of one type and support fast, vectorised maths.
- Check
shape,ndim,dtype; index with[row, col]and slices. - Boolean masks (
a[a > 10]) filter data; combine with&,|,~. axis=0= per column,axis=1= per row; broadcasting matches shapes automatically.- pandas uses all of these ideas.