PART 1 โ€ข FOUNDATIONS โ€ข LEVEL 02

Python, NumPy & Data Tools

Transform raw values into reliable, model-ready arrays and tables. Learn to reason about shape, vectorize calculations, broadcast safely, explore data and build reproducible workflows.

โฑ๏ธ 120โ€“150 min๐ŸŽฏ Beginner โ†’ Intermediate๐Ÿงช 2 Interactive Labs๐Ÿ’ผ Coding-Round Ready
CODEBHAVYA DATA LAB
>>> X.shape
(4, 3)
>>> X.mean(axis=0)
array([4.5, 5.5, 6.5])
>>> (X - X.mean(0)) / X.std(0)
array([[-1.34, -1.34, -1.34], ...])
LISTโ†’ARRAYโ†’INSIGHTโ†’MODEL

By the End of This Level, You Can

01Create NumPy arrays and explain shape, dimension, size and data type.
02Select, slice, filter, reshape and aggregate data without accidental copies.
03Apply broadcasting rules and diagnose incompatible shapes.
04Replace Python loops with readable vectorized computations.
05Load, inspect, clean, group and summarize tabular data with Pandas.
06Build reproducible analysis code suitable for projects and interviews.

Python Skills Used in Every Data Workflow

Recall these language tools before moving into numerical arrays.

SEQUENCELists & tuples

Store ordered values; slicing uses start, stop and step.

MAPPINGDictionaries

Represent named fields and key-value records.

ITERATIONComprehensions

Express small transformations clearly, but do not replace vectorization.

FUNCTIONReusable logic

Isolate transformations and make pipelines testable.

CONTEXTImports & environments

Use explicit dependencies and consistent package versions.

Why NumPy Is the Numerical Foundation of AI

Python lists are flexible containers. NumPy arrays are compact, typed, multidimensional structures built for numerical computation.

PYTHON LIST
values = [10, 20, 30]
doubled = [x * 2 for x in values]
  • Can mix object types
  • Loops execute at Python level
  • No native multidimensional shape
VS
NUMPY ARRAY
values = np.array([10, 20, 30])
doubled = values * 2
  • Usually one efficient dtype
  • Vectorized compiled operations
  • Shape and axis are explicit
Engineering rule: Prefer clear vectorized operations for bulk numerical work, but never sacrifice correctness or create enormous temporary arrays only to avoid a small loop.
DETAILED EXPLANATION

NumPy stores homogeneous numerical values in compact multidimensional arrays and executes operations in optimized compiled code. This makes whole-array computation faster and clearer than repeatedly interpreting Python loops. Most ML libraries exchange data using array-like tensors with the same shape-based reasoning.

WORKED INTUITION

Adding 10 to one million measurements is expressed as one array operation rather than one million Python statements.

AI / PLACEMENT CONNECTION

Vectorization is the bridge between mathematical notation and efficient model implementation.

COMMON MISCONCEPTION

Vectorized code can still create large temporary arrays. Speed does not remove the need to reason about memory.

Anatomy of an ndarray

An array is described by its values, axes, shape, size and data type.

axis 1 โ†’ features
102030401224364814284256
axis 0 โ†’ samples
DETAILED EXPLANATION

An ndarray is defined by its shape, number of dimensions, data type, size and memory strides. Shape tells how many values exist along each axis. Strides tell how many bytes must be moved to reach the next element along an axis, which explains why some views are inexpensive.

WORKED INTUITION

A dataset with 100 samples and 4 features normally has shape (100, 4): axis 0 selects samples and axis 1 selects features.

AI / PLACEMENT CONNECTION

Most array errors in interviews and models are shape errors rather than arithmetic errors.

COMMON MISCONCEPTION

A one-dimensional shape (4,) is not the same as a row matrix (1, 4) or column matrix (4, 1).

Data Types, Memory & Precision

The dtype controls representation, range, precision, memory and compatible operations.

int32 / int64Whole numbers

Counts, IDs and encoded categories. Watch integer overflow in limited types.

float32ML default in many models

Lower memory and faster accelerator computation, with reduced precision.

float64Higher precision

Common NumPy default for decimals and scientific calculations.

boolMasks and conditions

Stores True/False values for filtering and logical operations.

array.astype(np.float32)creates a converted array; confirm precision and memory trade-offs before converting.
DETAILED EXPLANATION

The dtype determines representation, range, precision and memory per value. Integers cannot represent fractions; floating-point numbers approximate real values with finite precision. Smaller types save memory and may accelerate hardware, but they can overflow or lose useful detail.

WORKED INTUITION

One million float64 values use about 8 MB, while float32 uses about 4 MB. The smaller type is common in neural networks.

AI / PLACEMENT CONNECTION

Mixed precision can accelerate training, while stable accumulation may still require a higher-precision type.

COMMON MISCONCEPTION

Do not compare floating-point results using exact equality after several calculations; use a tolerance such as np.allclose.

Create Arrays Intentionally

Choose a constructor that communicates the structure you need.

np.array(data)

Convert an existing sequence.

np.zeros(shape)

Initialize with zeros.

np.ones(shape)

Initialize with ones.

np.arange(start, stop, step)

Even integer-like spacing.

np.linspace(start, stop, count)

A fixed number of evenly spaced values.

rng.normal(size=shape)

Reproducible random samples through a generator.

DETAILED EXPLANATION

Array constructors should communicate intent: array converts known values, zeros and ones initialize storage, arange creates step-based sequences, linspace creates an exact count across an interval, and random generators create controlled samples. Always verify the resulting shape and dtype.

WORKED INTUITION

np.linspace(0, 1, 5) gives five evenly spaced values including both endpoints, which is useful for evaluating a model on a grid.

AI / PLACEMENT CONNECTION

Explicit construction makes experiments reproducible and prevents silent integer or shape assumptions.

COMMON MISCONCEPTION

Floating steps with arange can produce surprising endpoints because binary floating-point cannot represent every decimal exactly.

Indexing, Slicing & Boolean Masks

Select data by position or condition while keeping shape and copy behaviour visible.

ONE ELEMENTX[1, 2]

Row 1, column 2.

ROW SLICEX[0:2, :]

First two rows, all columns.

COLUMNX[:, 1]

All rows from column 1.

BOOLEAN MASKX[X > 30]

Flattened values satisfying a condition.

ROW FILTERX[X[:, 0] > 11]

Rows selected using the first feature.

FANCY INDEXX[[0, 2]]

Copy selected rows by index.

View vs copy: Basic slicing often returns a view that shares memory. Fancy indexing and boolean indexing generally return copies. Use .copy() when independent data is required.
DETAILED EXPLANATION

Indexing selects individual positions; slicing selects ranges; boolean masks select values satisfying a condition. Basic slicing usually returns a view that shares memory, while advanced or boolean indexing commonly returns a copy. Combining row and column conditions requires careful shape reasoning.

WORKED INTUITION

X[X[:, 2] > 10] selects complete rows whose third feature exceeds 10.

AI / PLACEMENT CONNECTION

Masks are used for filtering invalid rows, defining subgroups and evaluating model errors on important cases.

COMMON MISCONCEPTION

Changing a view may change the original array. Use copy explicitly when independent data is required.

Vectorization: Think in Whole Arrays

Express numerical intent over batches instead of repeatedly interpreting Python statements.

PYTHON LOOP
scaled = []
for value in values:
    scaled.append((value - mean) / std)

Correct, but Python coordinates every iteration.

VECTORIZED
scaled = (values - mean) / std

Shorter, clearer and normally much faster for numerical arrays.

Same asymptotic work: O(n)Different constant cost: vectorized operations execute optimized loops outside Python.
DETAILED EXPLANATION

Vectorization expresses an operation over an entire axis or array. NumPy then performs the repetitive work in optimized loops. The goal is not merely fewer lines: it is to expose the mathematical structure, reduce interpreter overhead and enable efficient low-level execution.

WORKED INTUITION

Predictions for all samples are X @ weights + bias instead of manually computing one weighted sum per row.

AI / PLACEMENT CONNECTION

Linear regression, neural layers and distance calculations are naturally expressed as vectorized operations.

COMMON MISCONCEPTION

A dense vectorized expression that duplicates huge arrays may be worse than a clear chunked computation.

Broadcasting Rules

Broadcasting performs elementwise operations on compatible shapes without physically copying every repeated value.

1Compare trailing dimensions

Start from the rightmost dimension and move left.

2Dimensions must match

Two dimensions are compatible when equal.

3Or one must be 1

A dimension of 1 can expand conceptually.

4Missing leading axes count as 1

This enables scalars, row vectors and column vectors.

(3, 4) + (4,)โœ“ โ†’ (3, 4)(3, 1) + (1, 4)โœ“ โ†’ (3, 4)(3, 4) + (3,)โœ• incompatible
DETAILED EXPLANATION

Broadcasting aligns shapes from the right. Dimensions are compatible when they are equal or one of them is 1; missing leading dimensions are treated as 1. The smaller operand is conceptually expanded without necessarily copying its data.

WORKED INTUITION

Subtracting a feature-mean vector of shape (4,) from data of shape (100, 4) centers every column.

AI / PLACEMENT CONNECTION

Broadcasting supports normalization, bias addition and batch operations throughout ML.

COMMON MISCONCEPTION

An operation can broadcast successfully but along the wrong semantic axis. A valid shape is not proof of correct meaning.

Aggregation and the Meaning of axis

The selected axis is reduced; the other axes remain in the result.

123456
X.sum()21

Reduce every axis to one scalar.

123456
X.sum(axis=0)[5, 7, 9]

Collapse rows; one result per column.

123456
X.sum(axis=1)[6, 15]

Collapse columns; one result per row.

DETAILED EXPLANATION

Aggregations reduce one or more axes. For a matrix, axis 0 removes the row dimension and summarizes each column; axis 1 removes the column dimension and summarizes each row. keepdims retains a length-one axis so later broadcasting remains explicit.

WORKED INTUITION

X.mean(axis=0, keepdims=True) produces one mean per feature with shape (1, features).

AI / PLACEMENT CONNECTION

Batch losses, feature statistics and normalization depend on choosing the intended reduction axis.

COMMON MISCONCEPTION

Memorizing โ€˜axis 0 means columnsโ€™ is fragile. Ask which axis disappears from the result.

Reshape, Transpose, Concatenate & Stack

Shape transformations change how values are organized. Always verify the result before supplying it to a model.

x.reshape(2, 3)

Change shape while preserving element count.

X.T

Reverse axes for a 2D matrix.

np.concatenate([A, B], axis=0)

Join existing arrays along an existing axis.

np.stack([A, B], axis=0)

Create a new axis and combine arrays.

x.reshape(-1, 1)

Infer row count and create one feature column.

np.squeeze(x)

Remove axes whose length is one.

DETAILED EXPLANATION

Reshape changes the logical arrangement without changing element count. Transpose reorders axes. Concatenate joins arrays along an existing axis, while stack creates a new axis. These operations determine how samples, features, channels and time steps are represented.

WORKED INTUITION

Stacking three vectors of shape (4,) along axis 0 produces a matrix of shape (3, 4).

AI / PLACEMENT CONNECTION

Correct shape transformations are essential before feeding image, sequence or tabular batches into a model.

COMMON MISCONCEPTION

Reshape may return a view or copy depending on memory layout; do not assume it is always free.

Pandas: From Records to Model-Ready Tables

A DataFrame adds named columns and indexes around typed arrays, making tabular analysis expressive.

01Loadpd.read_csv(...)

Specify paths, types and missing markers.

โ†’
02Inspectdf.info()

Check shape, types, nulls and sample rows.

โ†’
03Selectdf.loc[rows, cols]

Choose rows and columns explicitly.

โ†’
04Cleanfillna / dropna

Handle missingness using domain reasoning.

โ†’
05Summarizegroupby / agg

Compare categories and validate assumptions.

โ†’
06Exportto_csv(...)

Save clean artifacts with reproducible code.

student_idhoursattendancescore
CB1012.57852
CB1024.09173
CB103โ€”8668
df.isna().sum()reveals one missing value in hours. Investigate why it is missing before choosing a treatment.
DETAILED EXPLANATION

Pandas adds labelled rows and columns, heterogeneous types, missing-value handling, joins and group operations. A DataFrame should be treated as a table with a schema: each column needs a meaning, unit, valid range and expected availability time.

WORKED INTUITION

Group sales by region, aggregate count and mean, then join the summary to a reference table using a validated key.

AI / PLACEMENT CONNECTION

Most tabular ML pipelines begin with Pandas for inspection and end with numeric arrays for modelling.

COMMON MISCONCEPTION

Index alignment can silently produce missing values when combining Series with different labels.

Exploratory Data Analysis Is a Reliability Check

EDA is not decoration. It discovers data problems, distributions, relationships and dangerous assumptions before modelling.

๐Ÿ“Structure

Rows, columns, types, keys and units.

๐Ÿ•ณ๏ธMissingness

Count, pattern and reason for absent values.

๐Ÿ“ŠDistribution

Range, centre, spread, skew and unusual values.

๐Ÿ”—Relationships

Associations, redundancy and possible leakage.

๐ŸŽฏTarget

Balance, noise, ambiguity and time behaviour.

๐Ÿ‘ฅSubgroups

Coverage and performance-relevant differences.

Histogram distributionBox plot spread/outliersScatter plot two numeric variablesBar chart category comparisonHeatmap matrix patterns
DETAILED EXPLANATION

EDA tests whether the data can support the intended decision. Inspect distributions, missingness, duplicates, class balance, impossible values, target relationships and subgroup differences. Every chart should answer a question or expose an assumption that may affect modelling.

WORKED INTUITION

A sudden cluster of zero ages may represent missing values encoded incorrectly, not real newborn customers.

AI / PLACEMENT CONNECTION

EDA guides cleaning, splitting, baseline selection and later monitoring checks.

COMMON MISCONCEPTION

Exploring the final test target influences modelling choices and leaks evaluation information.

Reproducible Data Workflows

A result is trustworthy only when another run can recreate it from documented inputs and code.

01Use a random generatorrng = np.random.default_rng(42)
02Separate data and code

Do not manually edit source files between runs.

03Pin dependencies

Record Python and package versions.

04Validate assumptions

Assert required columns, shapes, ranges and uniqueness.

05Write functions

Convert notebook experiments into reusable transformations.

06Protect raw data

Save derived datasets separately with lineage.

DETAILED EXPLANATION

A reproducible workflow fixes random seeds where appropriate, records versions and parameters, preserves raw data, scripts transformations and validates schemas. Reproducibility means another run can reconstruct the same reasoning and resultโ€”not only that one random number repeats.

WORKED INTUITION

A saved pipeline contains imputation, scaling and model steps so prediction uses exactly the transformations fitted during training.

AI / PLACEMENT CONNECTION

Reliable experiments and production debugging depend on traceable data and code versions.

COMMON MISCONCEPTION

A seed alone cannot guarantee identical results across different hardware, parallel execution or library versions.

INTERACTIVE LEARNING โ€ข CODEBHAVYA PREMIUM VISUALIZER

๐ŸŽฌ NumPy Broadcasting โ€” Visual Flow

Watch a column vector and row vector expand conceptually into a 3 ร— 4 result.

LIVE
STEP 1 OF 7

Create a row vector

Start with four feature values arranged across columns.

Step 1 of 7
PROGRAM TRACING โ€ข LINE BY LINE

Trace Vectorized Standardization

Follow a NumPy array through mean, standard deviation, centring, scaling, masking and output.

Standardize and Select an Array

Standardization expresses each value as the number of standard deviations above or below the mean.

import numpy as np
scores = np.array([40., 55., 70., 85.])
mean = scores.mean()
std = scores.std()
centered = scores - mean
scaled = centered / std
mask = scores >= 70
selected = scaled[mask]
print(np.round(selected, 2))
STANDARD SCORE
z = (x โˆ’ ฮผ) / ฯƒ
  • ฮผ: mean of the feature.
  • ฯƒ: standard deviation of the feature.
  • z = 0: the value equals the mean.
  • Positive z: the value is above the mean.
  • Important: in ML, fit ฮผ and ฯƒ on training data only.

Practise Array and Data Reasoning

Attempt each problem independently. The checker verifies required NumPy/Pandas logic and exact task structure.

0 / 5Solved independently0 / 500Best score

Test Shape, Axis and Data Reasoning

Select one answer for every question. Results show your answer, the correct answer and an explanation.

Not checked yet

How Data-Stack Skills Appear in Hiring Rounds

Expect shape reasoning, transformations, debugging and compact Pandas tasksโ€”not only syntax definitions.

ROUND 01

Predict the Shape

Trace slicing, reshape, transpose and broadcasting without running code.

ROUND 02

Vectorize a Loop

Replace repeated Python operations with a correct array expression.

ROUND 03

Clean a Table

Inspect missing values, duplicates, types and invalid ranges.

ROUND 04

Explain the Pipeline

Defend transformations, train-only statistics and reproducibility choices.

CodeBhavya interview pattern:State the input shape โ†’ Apply the operation โ†’ State the output shape โ†’ Explain memory/copy behaviour โ†’ Mention one failure case.

๐ŸŽค Python, NumPy & Data โ€” Interview Questions

Answer aloud before opening each explanation.

The Data Workflow in One View

1Inspect

Know shape, dtype, missingness and meaning.

โ†’
2Transform

Use explicit vectorized and tabular operations.

โ†’
3Validate

Check outputs, invariants and train-only statistics.

โ†’
4Reproduce

Preserve code, versions, seeds and lineage.

In AI, most silent failures begin before model trainingโ€”with misunderstood shape, contaminated data or an irreproducible transformation.

Habits of Reliable Data Practitioners

01

Print or assert shape after every important transformation while learning.

02

Use axis only after saying in words which dimension must disappear.

03

Avoid chained Pandas assignment; use explicit .loc operations.

04

Fit scaling, imputation and encoding statistics on training data only.

05

Use np.allclose for floating-point array comparisons.

06

Profile before optimizing; readable vectorization is better than clever expressions.

Strengthen Array and Data Thinking

Predict the result first, then verify it in Python.

  1. 01

    Create a 3 ร— 4 array containing the numbers 1 through 12.

  2. 02

    Predict the shape of X[:, 1:3] when X.shape == (5, 4).

  3. 03

    Replace a loop that squares every value with a vectorized expression.

  4. 04

    Explain why shapes (5, 3) and (5,) cannot broadcast.

  5. 05

    Calculate column means while retaining a 2D shape using keepdims.

  6. 06

    Filter all rows whose second feature is greater than 10.

  7. 07

    Reshape 24 values into every possible two-dimensional shape.

  8. 08

    Demonstrate the difference between concatenate and stack.

  9. 09

    Find missing-value counts and percentages for every DataFrame column.

  10. 10

    Group sales by region and calculate count, mean and maximum.

  11. 11

    Write assertions for required columns, non-negative values and unique IDs.

  12. 12

    Explain why setting a random seed is necessary but not always sufficient for reproducibility.