Knowledge / Artificial Intelligence and Data Science / Python for data analysis: NumPy and pandas

Python for data analysis: NumPy and pandas

Artificial Intelligence and Data Science (B.E./B.Tech) · Programming and data · free study notes for exams, placements and interviews

In short

NumPy gives Python a fixed-type, contiguous n-dimensional array (ndarray) with vectorised arithmetic in compiled C, and pandas builds labelled one-dimensional Series and two-dimensional DataFrame structures on top of it for tabular work. Together they are the working layer of almost every Indian data-science job: loading CSV/Excel/SQL extracts, selecting and filtering rows, grouping, joining and aggregating, then handing clean arrays to scikit-learn. University AI&DS syllabi (AICTE model curriculum, UGC CBCS "Python for Data Science" / "Data Analytics Lab") examine array creation, indexing, slicing, broadcasting, aggregation, groupby, merges and reshaping, and GATE DA (Data Science & AI, a paper introduced in 2024) tests the same reasoning as pseudocode and output-prediction. Placement tests at TCS, Infosys, Wipro, Accenture, Cognizant, Mu Sigma, Fractal, ZS, Flipkart and bank analytics teams routinely ask "write this in pandas without a loop" and "what does this print". Expect both coding and explain-the-concept questions on axis semantics, views versus copies, and loc versus iloc.

Explained

Why NumPy: the ndarray and vectorisation

Indexing, slicing, views and copies

Broadcasting and axis semantics

pandas objects: Series, DataFrame and Index

Transform, group, join, reshape

Performance, interoperability and limits

Key points

Formulas and examples

Elements: size = d₁ × d₂ × … × dₙ; bytes: nbytes = size × itemsize (itemsize = 8 for float64/int64, 4 for float32/int32, 1 for int8/bool)
Broadcast result on each axis = max(len₁, len₂), legal only if one length is 1 or they are equal (compared right-to-left)
Population variance σ² = Σ(xᵢ − x̄)²/n (NumPy, ddof=0); Sample variance s² = Σ(xᵢ − x̄)²/(n − 1) (pandas, ddof=1)
s² = σ² × n/(n − 1) — conversion between the two
Matrix product C = A @ B is defined only if A is (m×n) and B is (n×p), giving (m×p); cost ≈ m·n·p multiply-adds
Inner-join row count with duplicate keys = Σ over keys (count in left × count in right)
Rows after melt of a frame with r rows and v value columns = r × v
Memory of a float64 column = rows × 8 bytes; of a category column ≈ rows × 1 byte (codes, ≤ 128 levels) + size of the category list

Example 1 - shape, memory and dtype economy. A sales extract has 50,00,000 rows (50 lakh) and these columns: amount (float64), qty (int64), state (object, 36 distinct values averaging 10 characters).

Example 2 - broadcasting and normalisation. Marks array M of shape (4, 3) — 4 students, 3 subjects:

M = [[80, 70, 90],
     [60, 50, 70],
     [90, 80, 100],
     [70, 60, 80]]

Example 3 - groupby, transform and share of total.

emp = pd.DataFrame({
    'city':   ['Pune','Pune','Mumbai','Mumbai','Mumbai','Chennai'],
    'salary': [60000, 80000, 120000, 100000, 80000, 50000]})

**Example 4 - merge cardinality and how=.** orders has 5 rows with cust_id = [1, 1, 2, 3, 5]; cust has 4 rows with cust_id = [1, 2, 2, 4].

howMatching logicRows in result
innerid 1: 2×1 = 2; id 2: 1×2 = 24
leftthe 4 inner rows + unmatched orders 3 and 56
rightthe 4 inner rows + unmatched cust 45
outer4 inner + orders 3, 5 + cust 47

**Example 5 - .loc vs .iloc and view vs copy (output prediction).**

s = pd.Series([10, 20, 30, 40], index=['a','b','c','d'])
s.loc['a':'c']     # a 10, b 20, c 30   -> 3 items (end INCLUSIVE)
s.iloc[0:3]        # a 10, b 20, c 30   -> 3 items (end EXCLUSIVE)
s.iloc[0:2]        # a 10, b 20         -> 2 items

a = np.arange(6)         # [0 1 2 3 4 5]
v = a[1:4]; v[0] = 99    # v is a VIEW  -> a becomes [0 99 2 3 4 5]
c = a[[1,2,3]]; c[0] = 7 # c is a COPY  -> a unchanged: [0 99 2 3 4 5]
print(a.sum())           # 0+99+2+3+4+5 = 113
TaskSlow (avoid)Fast (vectorised)
Add 18% GSTdf.apply(lambda r: r.amt*1.18, axis=1)df['amt'] * 1.18
Flag high valuefor i, r in df.iterrows(): ...np.where(df.amt > 50000, 'High', 'Low')
Group mean fillloop per groupdf.groupby('city')['sal'].transform('mean')
Uppercase namesdf.name.apply(str.upper)df.name.str.upper()
Build rowsdf = pd.concat([df, row]) in a loopcollect in a list, pd.concat(list) once

Where it is used

Interview questions

Common mistakes

Related topics

Python essentials · Data cleaning and feature engineering · SQL queries and joins · Advanced SQL: subqueries, CTEs and window functions · Data visualisation · Python ML libraries: scikit-learn, PyTorch and TensorFlow

Open in the Knowledge reader →Find jobs →