1. LPU MCA Semester 1
  2. CAB107
  3. Unit 2

CAB107 · Unit 2: Python for AI and data science

Pandas for data manipulation and analysis

10 practice questions · in the MTE and ETE syllabus

Key points

  • Series is 1D, DataFrame is a 2D labelled table
  • loc is label-based, iloc is position-based
  • groupby splits, aggregates and combines
  • merge joins on a key like a SQL join

Pandas provides two main structures: a Series, a one-dimensional labelled array, and a DataFrame, a two-dimensional table with labelled rows and columns. A DataFrame is a collection of Series sharing an index.

Common operations:

TaskCode
Load a CSVpd.read_csv('f.csv')
Label-based selectiondf.loc[row_label, col]
Position-based selectiondf.iloc[0, 1]
Filter rowsdf[df['age'] > 30]
Group and aggregatedf.groupby('city')['sales'].mean()
Missing valuesdf.isna().sum()
import pandas as pd
df = pd.DataFrame({'city': ['A', 'B', 'A'], 'sales': [10, 20, 30]})
print(df.groupby('city')['sales'].sum())

This prints a Series indexed by city with A equal to 40 and B equal to 20. loc uses labels and includes the end of a label slice, whereas iloc uses integer positions and excludes the end. merge joins tables on a key, much like a SQL join, and concat stacks them.

Exam trap: loc versus iloc. After filtering or sorting, row labels no longer match positions, so the two can return different rows.

Try two questions

Question 1 · Tier 1, Recall

Which Pandas structure represents a two-dimensional table with labelled rows and columns?

  1. DataFrame
  2. Series
  3. ndarray
  4. Tuple
Show the answer

A. DataFrame is the main Pandas object for tabular data.

Why not B: A Series is one-dimensional.

Why not C: ndarray is the NumPy array and carries no column labels.

Why not D: A tuple is a built-in sequence type, not a table.