Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔢 Week 2 – NumPy & Pandas  ·  Day 08

Day 8: NumPy Arrays

⏱ 90 min📶 Beginner🎯 100% self-study
Day 8 / 60

✅ Today you will learn

  • Why NumPy is 50× faster than lists
  • Create arrays: array, arange, linspace, zeros, ones
  • shape, ndim, size and dtype
  • Index, slice and filter with boolean masks
  • reshape, flatten, stack and concatenate

🏢 In the real world

A weather company stores readings from 2,000 sensors every 10 minutes – millions of numbers a day. NumPy arrays let them compute daily averages for all sensors in a fraction of a second; plain Python lists would take minutes.

Why NumPy?

NumPy stores numbers of one type in one continuous block of memory and runs maths in fast C code. Pandas, scikit-learn and almost every data library are built on top of it.

Python
import time
import numpy as np
n = 2_000_000
py_list = list(range(n))
arr = np.arange(n)
t = time.perf_counter(); s1 = sum(x * 2 for x in py_list); t1 = time.perf_counter() - t
t = time.perf_counter(); s2 = (arr * 2).sum(); t2 = time.perf_counter() - t
print("Same answer:", s1 == s2)
print("NumPy is roughly", round(t1 / t2), "times faster on this computer")
Same answer: True NumPy is roughly 4 times faster on this computer

The exact speed-up depends on your machine, but it is usually tens of times faster.

Creating arrays

Python
import numpy as np
marks = np.array([78, 92, 65, 88, 71])
print(marks, marks.dtype)
print(np.arange(0, 20, 5))            # start, stop, step
print(np.linspace(0, 1, 5))           # 5 equal points from 0 to 1
print(np.zeros(3), np.ones((2, 3)))
print(np.full(4, 99), np.eye(3, dtype=int))
[78 92 65 88 71] int64 [ 0 5 10 15] [0. 0.25 0.5 0.75 1. ] [0. 0. 0.] [[1. 1. 1.] [1. 1. 1.]] [99 99 99 99] [[1 0 0] [0 1 0] [0 0 1]]

shape, ndim, size, dtype

Python
import numpy as np
# rows = 4 students, columns = maths, science, english
scores = np.array([[78, 82, 69],
                   [92, 88, 95],
                   [65, 70, 58],
                   [88, 79, 84]])
print("shape:", scores.shape, "| ndim:", scores.ndim, "| size:", scores.size, "| dtype:", scores.dtype)
prices = np.array([499, 1299.5, 89])
print(prices.dtype, prices.astype(int))
shape: (4, 3) | ndim: 2 | size: 12 | dtype: int64 float64 [ 499 1299 89]
scores (4 × 3)
mathsscienceenglish
0788269
1928895
2657058
3887984
scores[1] is row 1 · scores[:, 1] is the science column

Indexing and slicing

Python
import numpy as np
scores = np.array([[78, 82, 69], [92, 88, 95], [65, 70, 58], [88, 79, 84]])
print(scores[1])            # second student
print(scores[1, 2])         # second student, english
print(scores[:, 0])         # all maths marks
print(scores[1:3, :2])      # students 1–2, maths & science
print(scores[-1, -1])       # last student, last subject
[92 88 95] 95 [78 92 65 88] [[92 88] [65 70]] 84

Boolean masks – filtering without loops

Python
import numpy as np
temps = np.array([31.2, 34.8, 41.5, 39.0, 44.1, 29.7, 42.3])
hot = temps > 40
print(hot)
print("Hot days:", temps[hot], "| count:", hot.sum())
print("Mild days:", temps[(temps >= 30) & (temps <= 40)])
print("Index of hottest day:", temps.argmax())
temps[temps > 43] = 43            # cap extreme sensor values
print(temps)
[False False True False True False True] Hot days: [41.5 44.1 42.3] | count: 3 Mild days: [31.2 34.8 39. ] Index of hottest day: 4 [31.2 34.8 41.5 39. 43. 29.7 42.3]
⚠️ Use & and |, not and / or

For arrays write (a > 1) & (a < 5) with brackets. Python’s and works only on single True/False values and gives an error with arrays.

Reshape, stack and concatenate

Python
import numpy as np
monthly = np.arange(1, 13) * 100          # 12 months of sales
print(monthly.reshape(4, 3))             # 4 quarters × 3 months
print(monthly.reshape(4, -1).sum(axis=1))  # quarter totals (-1 = work it out)
a, b = np.array([1, 2, 3]), np.array([4, 5, 6])
print(np.vstack([a, b]))
print(np.hstack([a, b]), np.concatenate([a, b]).shape)
print(monthly.reshape(4, 3).flatten()[:5])
[[ 100 200 300] [ 400 500 600] [ 700 800 900] [1000 1100 1200]] [ 600 1500 2400 3300] [[1 2 3] [4 5 6]] [1 2 3 4 5 6] (6,) [100 200 300 400 500]

Real example: class report card

Python
import numpy as np
names = np.array(["Aman", "Priya", "Rahul", "Sneha", "Kabir"])
scores = np.array([[78, 82, 69], [92, 88, 95], [35, 41, 28], [88, 79, 84], [55, 62, 60]])
avg = scores.mean(axis=1)
print("Averages:", avg.round(1))
print("Topper  :", names[avg.argmax()], avg.max().round(1))
print("Failed (<40):", names[avg < 40])
print("Subject averages (M, S, E):", scores.mean(axis=0).round(1))
print("Students above 80 in all subjects:", names[(scores > 80).all(axis=1)])
Averages: [76.3 91.7 34.7 83.7 59. ] Topper : Priya 91.7 Failed (<40): ['Rahul'] Subject averages (M, S, E): [69.6 70.4 67.2] Students above 80 in all subjects: ['Priya']

🏅 Job skills unlocked today

✔ Create and inspect NumPy arrays✔ Slice rows and columns of a 2-D array✔ Filter with boolean masks✔ Reshape data into new layouts

Practice tasks

🏋️ Practice – do it yourself

Task 1: Create an array of 10 daily step counts and print the days (index) with more than 8,000 steps.
Show solution
Python
import numpy as np
steps = np.array([6500, 9200, 7800, 10400, 5600, 8800, 12000, 4300, 8100, 7600])
print(np.where(steps > 8000)[0])
[1 3 5 6 8]
Task 2: Reshape np.arange(1, 25) into 6 rows × 4 columns and print the sum of each column.
Show solution
Python
import numpy as np
m = np.arange(1, 25).reshape(6, 4)
print(m.sum(axis=0))
[66 72 78 84]
Task 3: In the report-card example, add 5 grace marks to every science mark (column 1) but cap at 100.
Show solution
Python
import numpy as np
scores = np.array([[78, 82, 69], [92, 98, 95], [35, 41, 28]])
scores[:, 1] = np.minimum(scores[:, 1] + 5, 100)
print(scores)
[[ 78 87 69] [ 92 100 95] [ 35 46 28]]

Quick quiz

🧠 Quick Quiz – test yourself

1. np.arange(2, 10, 3) gives…
Start 2, step 3, stop before 10.
2. scores.shape is (4, 3). How many students (rows)?
shape is (rows, columns).
3. scores[:, 0] selects…
: means all rows, 0 means column 0.
4. Which correctly filters values between 10 and 20?
Use & with brackets for element-wise AND.
5. reshape(4, -1) on 12 values gives shape…
-1 lets NumPy compute the missing size: 12 / 4 = 3.

Interview corner

💼 Interview Corner

Why is NumPy faster than Python lists?

Arrays store one data type in contiguous memory, operations run in optimised C loops (vectorisation) without Python overhead per element, and they use CPU features like SIMD.

What does axis=0 vs axis=1 mean?

axis=0 works down the rows and gives one result per column; axis=1 works across columns and gives one result per row.

Summary

  • NumPy arrays are fast, typed, n-dimensional containers.
  • shape = (rows, cols); index with [row, col]; slice with :.
  • Boolean masks filter data without loops.
  • reshape, vstack and hstack rearrange data.
➡️ Next

Day 9: maths on whole arrays, broadcasting rules, aggregation and random numbers for simulations.

Frequently Asked Questions

Can a NumPy array hold text?
Yes, but it is designed for numbers. For mixed tables use pandas DataFrames.
What is the difference between a view and a copy?
Slicing returns a view that shares memory with the original – changing it changes the original. Use .copy() when you need independence.
Do I need to learn all NumPy functions?
No. Arrays, indexing, masks, aggregation and broadcasting (Day 9) cover 90% of data work.
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 9: NumPy Maths, Broadcasting & Random Your progress: 8 / 60 (13%) · Lesson 9 / 60 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free