Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Python libraries for data analysis

Practical study notes on the main Python libraries used in data analysis (NumPy, pandas, matplotlib/seaborn, SciPy, scikit-learn, Plotly/Bokeh), how they work, key operations and idioms, with runnable examples and common exam-style questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Python libraries for data analysis provide ready-made, tested tools that let engineers load, clean, transform, analyse and visualise data quickly. An engineer uses these libraries in tasks such as preprocessing sensor logs, exploring datasets for machine learning, producing reports and plots for stakeholders, and performing statistical tests.

Key ideas

Define terms first, then explain core concepts and exact rules you must remember for exams.

  • NumPy: a library providing the ndarray type — a fixed-size, homogeneous, n-dimensional array of values stored in memory with strides (often contiguous, but not required). Use it when you need fast numerical operations on vectors and matrices. Assumption: elements share one dtype (typically numeric, e.g., float64).

  • array (ndarray): an ordered, indexable collection of values (single dtype) with a shape (tuple of integers). Exact property: element access by integer indices starting at 0; multi-dimensional indexing uses tuples of indices.

  • vectorization: writing operations that act on whole arrays (ndarrays) at once instead of Python loops. Exact statement: A vectorized NumPy operation applies element-wise arithmetic using compiled C loops under the hood, so for an array of length n the cost is O(n) in C rather than O(n) Python bytecode operations.

  • broadcasting: a set of rules that lets arrays of different shapes be used together in arithmetic. Exact rule (as universities expect): 1) Align the shapes of the two arrays by prepending 1s to the smaller shape so both have the same number of dimensions. 2) For each dimension from rightmost to leftmost, the sizes are compatible if they are equal or one of them is 1. 3) The resulting broadcast shape is the maximum size along each dimension. If any dimension is incompatible, broadcasting raises an error. (Draw: two shape tuples, align them right, show one has 1 and other 3 — label compatible.)

  • pandas: a library that provides the Series (1‑D labeled array) and DataFrame (2‑D labeled table with rows and columns). Exact definitions: A Series is an ordered mapping from an index to values; a DataFrame is a mapping from column labels to Series of equal length. Assumptions: columns may have different dtypes; indices may be non-unique, but many operations are simpler with unique indices, and alignments/joins can yield repeated rows when indices or keys are non-unique.

  • indexing and selection: two common methods: loc selects by label (inclusive slices), iloc by integer positions (exclusive stop for slices like Python). Exact behavior: df.loc[a:b] includes both a and b if they exist as labels; df.iloc[i:j] includes rows i through j-1.

  • groupby-aggregate-transform-filter: Group data by key(s), then compute an aggregation (reduces each group to a single summary value), a transformation (returns a structure with same shape as original), or a filter (keeps groups meeting a predicate). Common exam derivation: To compute group means you call df.groupby('key')['value'].mean(); internally pandas partitions rows by key and applies the reduction.

  • merge / join / concat: operations to combine DataFrames. Exact definitions: merge combines two DataFrames on key columns (SQL-like joins: inner, left, right, outer). concat appends along rows or columns. Assumption: key columns may need identical dtypes.

  • pivot / pivot_table: reshape long data to a wide table. pivot requires unique index/column pairs; pivot_table supports aggregation when pairs are not unique.

  • matplotlib / seaborn: plotting libraries. Figure is the top-level container; Axes are the area where data is plotted. Exact usage pattern: fig, ax = plt.subplots() then ax.plot(x,y).

  • scikit-learn: a library for machine learning models and pipelines. It follows the estimator API: fit(X, y) trains a model, predict(X) applies it. Exact contract: X is a 2-D array-like of shape (n_samples, n_features); y is 1-D of length n_samples.

  • Complexity and performance rules to remember: vectorized NumPy/pandas operations are typically orders of magnitude faster than pure Python loops because they operate in compiled code; copying data (e.g., using .copy()) costs O(n) memory and time.

Diagrams to draw for exam: 1) Broadcasting example: draw two shape tuples aligned right, show prepended 1s, mark compatible/incompatible dims. 2) DataFrame diagram: columns labeled, rows with index values; show loc and iloc on the diagram.

Formulas

List of syntax and short explanation to remember (each line is a command or pattern and when it applies):

import numpy as np — import NumPy as alias np.

a = np.array([1, 2, 3], dtype=float) — create an ndarray; dtype sets element type.

a.shape — returns shape tuple (rows, cols, ...).

a.reshape(m, n) — returns view or copy reshaped to (m, n) if total size matches.

b + a — element-wise addition; works with broadcasting rules described above.

np.mean(a, axis=0) — compute mean along axis 0 (rows aggregated); axis numbering: 0 for rows, 1 for columns.

import pandas as pd — import pandas.

df = pd.DataFrame(data, columns=['A','B']) — create DataFrame from structured data.

df = pd.read_csv('file.csv') — read a CSV into a DataFrame.

df.to_csv('out.csv', index=False) — write a DataFrame to CSV (no row index).

df['col'] or df.col — select column (Series).

df.loc[label], df.loc[start_label:end_label] — label-based selection (inclusive).

df.iloc[i:j] — integer-position selection (Python slice rules, stop exclusive).

df.groupby('key')['val'].agg(['mean','sum']) — group by column key and aggregate val with mean and sum.

pd.merge(df1, df2, on='key', how='inner') — SQL-like join; how ∈ {inner,left,right,outer}.

df.pivot_table(index='row_key', columns='col_key', values='val', aggfunc='mean') — reshape with aggregation.

import matplotlib.pyplot as plt — import plotting API.

fig, ax = plt.subplots(); ax.plot(x, y, label='line'); ax.set_title('Title'); fig.savefig('out.png') — basic plotting pattern.

from sklearn.model_selection import train_test_split — split data for ML.

from sklearn.linear_model import LinearRegression then model = LinearRegression(); model.fit(X_train, y_train); y_pred = model.predict(X_test) — sklearn estimator pattern.

Worked examples

Each program is complete and prints the outputs shown; minor formatting (spacing/alignment) may vary by library version. Run these under Python 3 with numpy and pandas installed.

Example 1 — NumPy broadcasting and mean (run as script):

import numpy as np
# 2x3 array
A = np.array([[1.0, 2.0, 3.0],
              [4.0, 5.0, 6.0]])
# 1D length-3 vector
b = np.array([10.0, 20.0, 30.0])
# Broadcasting: add b to each row of A
C = A + b
# Mean across rows (axis=0)
col_mean = np.mean(C, axis=0)
print('A =')
print(A)
print('b =', b)
print('C = A + b =')
print(C)
print('Column means of C =', col_mean)

Sample output exactly:

A = [[1. 2. 3.] [4. 5. 6.]] b = [10. 20. 30.] C = A + b = [[11. 22. 33.] [14. 25. 36.]] Column means of C = [12.5 23.5 34.5]

Example 2 — pandas groupby and merge (run as script):

import pandas as pd
# student marks
students = pd.DataFrame({
    'roll': [1,2,3,4,5,6],
    'class': ['A','A','B','B','B','A'],
    'marks': [80, 70, 85, 90, 75, 65]
})
# class info
classes = pd.DataFrame({
    'class': ['A','B'],
    'teacher': ['Ms Sharma','Mr Kumar']
})
# group average marks by class
avg = students.groupby('class')['marks'].mean().reset_index().rename(columns={'marks':'avg_marks'})
# merge with class info
summary = pd.merge(classes, avg, on='class', how='left')
print('students:')
print(students.to_string(index=False))
print('\nclasses:')
print(classes.to_string(index=False))
print('\navg marks by class:')
print(avg.to_string(index=False))
print('\nsummary:')
print(summary.to_string(index=False))

Sample output (formatting such as spacing/alignment may vary by pandas version; numeric/text values shown are correct):

students: roll class marks 1 A 80 2 A 70 3 B 85 4 B 90 5 B 75 6 A 65

classes: class teacher A Ms Sharma B Mr Kumar

avg marks by class: class avg_marks A 71.66666666666667 B 83.33333333333333

summary: class teacher avg_marks A Ms Sharma 71.66666666666667 B Mr Kumar 83.33333333333333

Example 3 — pivot_table from long to wide (run as script):

import pandas as pd
# long format sales data
sales = pd.DataFrame({
    'store': ['S1','S1','S2','S2','S1','S2'],
    'month': ['Jan','Feb','Jan','Feb','Mar','Mar'],
    'sales': [100, 150, 200, 180, 130, 210]
})
pt = sales.pivot_table(index='store', columns='month', values='sales', aggfunc='sum')
print('sales (long):')
print(sales.to_string(index=False))
print('\npivot table (stores x months):')
print(pt.fillna(0).to_string())

Sample output exactly:

sales (long): store month sales S1 Jan 100 S1 Feb 150 S2 Jan 200 S2 Feb 180 S1 Mar 130 S2 Mar 210

pivot table (stores x months): month Feb Jan Mar store
S1 150 100 130 S2 180 200 210

(Notes: exact formatting may vary slightly by pandas version, but numeric values shown are correct.)

Common mistakes

  • Modifying a sliced view thinking it's a copy: some pandas/NumPy operations return views, other times copies; use .copy() if you need an independent copy.
  • Using Python loops for element-wise numeric ops instead of NumPy vectorized ops — very slow for large arrays.
  • Merging on columns with different dtypes (e.g., one int, one str) — merge returns empty joins or errors.
  • Using pivot when index/column pairs are not unique — use pivot_table with aggfunc instead.

For your exam

Kinds of questions and what full-marks answers include:

  • Definitions: Define ndarray, DataFrame, broadcasting, vectorization. Include assumptions (homogeneous dtype for ndarray; labeled rows/cols for DataFrame) and concise examples.
  • Short notes: Compare NumPy and pandas: when to use each; explain groupby/merge/pivot_table with short code snippets and time complexity notes (aggregation is O(n) over grouped rows).
  • Derivations: Show step-by-step broadcasting compatibility for two shapes (draw and label). Provide the algorithm of groupby (partition-apply-combine) with steps.
  • Programs: Small scripts like the Worked examples above. Show input data, code, and exact printed output. Explain each line where asked.
  • Diagrams: Draw DataFrame as table with labeled index and columns; show loc and iloc ranges. For broadcasting draw aligned shapes.

A full-marks answer includes: exact definitions with bolded terms, code or commands where applicable, an explanation of assumptions and edge cases, and a small example or diagram.

Quick check

  1. What is the rule for broadcasting two arrays?
  2. What does df.groupby('k')['v'].mean() do?
  3. Which method selects rows by integer positions: loc or iloc?

Answers: 1) Align shapes on right, sizes compatible if equal or one is 1 in every dimension; result shape is max per dimension. 2) Groups DataFrame df by column 'k' and computes the mean of column 'v' for each group. 3) iloc.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?