NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python
P12.6 NumPy 2D Arrays: Rows, Columns and Axis
Why. Tables have rows and columns. A 2D array is a table of numbers, and axis decides whether you total down columns or across rows.
What. arr[row, col] picks a cell. axis=0 works down the columns, axis=1 across the rows.
| Week 1 | Week 2 | Week 3 | |
|---|---|---|---|
| Pune | 120 | 135 | 128 |
| Mumbai | 210 | 198 | 225 |
How to read this table: each row is one store; each column is one week; values are orders.
How.
Work with a 2D array
- Create with a list of lists.
- Check
.shape→ (rows, columns). - Pick a cell with
[row, col], a row with[row], a column with[:, col]. - Sum with
axis=0(per column) oraxis=1(per row).
Worked example A — Create and read.
Step 1 — What we do. The store-by-week table above.
Step 2 — Type and run this code.
import numpy as np
orders = np.array([[120, 135, 128],
[210, 198, 225]])
print(orders.shape)
print(orders[1, 2])
print(orders[:, 0])
Step 3 — Output you should see.
(2, 3)
225
[120 210]
Step 4 — What it means. Shape (2, 3) = 2 rows, 3 columns. [1, 2] = Mumbai week 3. [:, 0] = all rows, week 1.
Worked example B — Totals by store and by week.
Step 1 — What we do. We sum across and down.
Step 2 — Type and run this code.
import numpy as np
orders = np.array([[120, 135, 128],
[210, 198, 225]])
print("Per store:", orders.sum(axis=1))
print("Per week:", orders.sum(axis=0))
Step 3 — Output you should see.
Per store: [383 633]
Per week: [330 333 353]
Step 4 — What it means. axis=1 adds across each row (store totals). axis=0 adds down each column (week totals). pandas uses the same axis idea.
Ravindra Bagale's Tip
Remember axis like this: axis=0 collapses the rows (answer per column), axis=1 collapses the columns (answer per row).
Ravindra Bagale's Tip – मराठी
Axis असं लक्षात ठेवा: axis=0 rows एकत्र करतो (प्रत्येक column चं उत्तर), axis=1 columns एकत्र करतो (प्रत्येक row चं उत्तर).
Ravindra Bagale's Tip – हिंदी
Axis ऐसे याद रखो: axis=0 rows को समेटता है (हर column का जवाब), axis=1 columns को समेटता है (हर row का जवाब).
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.