By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
For Data Scientists Who Need to Ship Code, Not Just Pass Exams
Pandas is the Swiss Army knife of Python data science. If you’ve ever: - Cleaned a messy CSV from a client, - Merged two datasets to find trends, - Or built a quick prototype for a stakeholder,
…you’ve likely used Pandas. Series and DataFrame are its two core structures: - Series = A single column of data (like a Python list, but smarter).- DataFrame = A spreadsheet-like table (rows + columns).
csv
chunksize
df[df['age'] > 30]
KeyError
groupby
merge
values
index
0, 1, 2, ...
dtype
int64
object
loc
iloc
shape
(rows, columns)
columns
dtypes
join
df.index.is_unique
df.loc['row_label', 'col_name']
df.iloc[0, 1]
NaN
5 + NaN = NaN
df.dropna()
df.fillna()
# Fast (vectorized) df['revenue'] = df['price'] * df['quantity'] ```
GROUP BY
sum
mean
python df.groupby('region')['sales'].sum() # Total sales per region
concat
Task: Load two CSV files (sales data + product info), merge them, and generate a pivot table of revenue by region.
pip install pandas
sales.csv
order_id
product_id
quantity
region
products.csv
price
category
import pandas as pd # Load CSVs sales = pd.read_csv('sales.csv') products = pd.read_csv('products.csv') # Verify print(sales.head()) # First 5 rows print(products.dtypes) # Check data types
Expected output:
order_id product_id quantity region 0 1 10 2 East 1 2 20 1 West ...product_id int64 price float64 category object dtype: object
# Check for missing values print(sales.isna().sum()) # Drop rows with missing 'region' sales = sales.dropna(subset=['region']) # Convert 'product_id' to string (to match products.csv) sales['product_id'] = sales['product_id'].astype(str) products['product_id'] = products['product_id'].astype(str)
# Merge sales + products on 'product_id' merged = pd.merge( sales, products, on='product_id', how='left' # Keep all sales records (even if product missing) ) # Calculate revenue merged['revenue'] = merged['quantity'] * merged['price']
# Revenue by region and category pivot = merged.pivot_table( index='region', columns='category', values='revenue', aggfunc='sum', fill_value=0 # Replace NaN with 0 ) print(pivot)
category Electronics Furniture Clothing region East 5000.0 2000.0 1500.0 West 3000.0 1000.0 2000.0
pivot.to_excel('sales_report.xlsx', sheet_name='Revenue')
int32
python df['user_id'] = df['user_id'].astype('int32')
apply
python chunk_iter = pd.read_csv('big_file.csv', chunksize=10000) for chunk in chunk_iter: process(chunk)
python assert sales['quantity'].min() >= 0, "Negative quantities found!"
try-except
python try: df = pd.read_csv('data.csv') except FileNotFoundError: print("File missing! Using backup...") df = pd.read_csv('backup.csv')
user_id
uid
python # Filter out test orders (order_id starts with 'TEST') df = df[~df['order_id'].str.startswith('TEST')]
pd.NA
None
python print(f"Merged DataFrame shape: {merged.shape}")
python print(df.memory_usage(deep=True))
df.loc[0]
.copy()
TypeError
df.fillna(0)
df.loc[df['age'] > 30]
df.groupby('department')['salary'].mean()
df.groupby('department').mean()['salary']
how='left'
how='inner'
left
inner
df.loc['row1', 'colA']
inplace=True
Task: Given a DataFrame df with columns ['name', 'score', 'grade'], create a new column 'pass_fail' where: - 'pass' if score >= 70 and grade is not 'F'.- 'fail' otherwise.
df
['name', 'score', 'grade']
'pass_fail'
'pass'
score >= 70
grade
'F'
'fail'
Solution:
df['pass_fail'] = np.where( (df['score'] >= 70) & (df['grade'] != 'F'), 'pass', 'fail' )
Why it works: np.where is vectorized and handles conditions efficiently.
np.where
pd.Series([1, 2, 3], index=['a', 'b', 'c'])
pd.DataFrame({'col1': [1, 2], 'col2': ['a', 'b']})
pd.read_csv('file.csv', dtype={'id': 'int32'})
df[['name', 'age']]
df.groupby('region')['sales'].sum()
pd.merge(df1, df2, on='key', how='left')
df.pivot_table(index='region', columns='category', values='sales')
aggfunc='sum'
fillna
dropna
df.to_excel('file.xlsx', index=False)
index=False
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.