Pandas is the universal Swiss Army knife of tabular data wrangling in Python. In this class, we eliminate common beginner traps (like SettingWithCopyWarning), master precision indexing with .loc and .iloc, and learn memory optimization techniques.
| Feature | .loc[row_labels, col_labels] |
.iloc[row_positions, col_positions] |
|---|---|---|
| Addressing Method | Explicit index/column label strings. | Integer zero-based coordinates (0, 1, 2...). |
| Slice Boundaries | Inclusive of endpoints ('a':'c' includes 'c'). |
Exclusive of endpoints (0:3 includes 0, 1, 2). |
| Conditional Filters | Directly accepts boolean Series masks. | Requires raw boolean arrays or integer offsets. |
| Standard Example | df.loc[df['churn'] == 1, ['name', 'age']] |
df.iloc[0:10, [0, 2]] |
import pandas as pd
import numpy as np
def optimize_dataframe_memory(df: pd.DataFrame) -> pd.DataFrame:
"""Downcasts numeric types and converts objects to categories to slash RAM footprint."""
initial_mem = df.memory_usage(deep=True).sum() / (1024**2)
df_opt = df.copy()
for col in df_opt.columns:
col_type = df_opt[col].dtype
if col_type == 'int64':
df_opt[col] = pd.to_numeric(df_opt[col], downcast='integer')
elif col_type == 'float64':
df_opt[col] = pd.to_numeric(df_opt[col], downcast='float')
elif col_type == 'object':
num_unique = df_opt[col].nunique()
num_total = len(df_opt[col])
# If unique values are less than 50% of rows, convert to category
if num_unique / num_total < 0.50:
df_opt[col] = df_opt[col].astype('category')
final_mem = df_opt.memory_usage(deep=True).sum() / (1024**2)
print(f"Memory reduced from {initial_mem:.2f} MB → {final_mem:.2f} MB ({(1 - final_mem/initial_mem)*100:.1f}% savings)")
return df_opt
# Clean, readable data transformation pipeline
target_countries = ['US', 'CA', 'UK']
df_cleaned = (
df
.query("spend > 0 and country in @target_countries")
.assign(
log_spend=lambda x: np.log1p(x['spend']),
high_spender=lambda x: (x['spend'] >= 500).astype(int)
)
.drop(columns=['raw_timestamp'], errors='ignore')
.sort_values(by='spend', ascending=False)
)
What is a Series vs. a DataFrame in Pandas? (Answer: A Series is a 1-dimensional labeled homogeneous array; a DataFrame is a 2-dimensional labeled tabular data structure where each column is an individual Series sharing a common index).
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Understand the core numerical array structures underlying Pandas series.
Aggregate, transform, and reshape DataFrames with multi-level grouping.
Use Pandas methods (.fillna, .dropna, .interpolate) for data hygiene.
Engineer tabular features directly from raw Pandas DataFrames.