- LPU MCA Semester 1
- CAB107
- 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:
| Task | Code |
|---|---|
| Load a CSV | pd.read_csv('f.csv') |
| Label-based selection | df.loc[row_label, col] |
| Position-based selection | df.iloc[0, 1] |
| Filter rows | df[df['age'] > 30] |
| Group and aggregate | df.groupby('city')['sales'].mean() |
| Missing values | df.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
Which Pandas structure represents a two-dimensional table with labelled rows and columns?
- DataFrame
- Series
- ndarray
- 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.