Pandas is Python's premier tabular and time-series data analysis library, built on NumPy. Its core data structures are the 2D tabular DataFrame with labeled axes and the 1D labeled Series, delivering high-performance alignment, missing value cleaning, groupby aggregations, and relational joins.
🔗 Related Cheat Sheets: NumPy Cheat Sheet · Scikit-Learn Cheat Sheet · Seaborn Cheat Sheet · Bokeh Cheat Sheet · Data Analysis Methods · Python Cheat Sheet
1. End-to-End Quickstart Example
import pandas as pd
import numpy as np
# 1. Create DataFrame
data = {
'Country': ['China', 'USA', 'India', 'Germany', 'China'],
'Department': ['Tech', 'Finance', 'Tech', 'Finance', 'Tech'],
'Salary': [12000, 15000, 9000, 14000, 13000],
'Bonus': [2000, np.nan, 1500, 2500, 3000]
}
df = pd.DataFrame(data)
# 2. Clean data (impute missing values and compute total comp)
df['Bonus'] = df['Bonus'].fillna(0)
df['Total_Comp'] = df['Salary'] + df['Bonus']
# 3. Filter using loc
tech_high_earners = df.loc[(df['Department'] == 'Tech') & (df['Salary'] >= 10000)]
# 4. GroupBy aggregation
dept_summary = df.groupby('Department').agg(
Avg_Salary=('Salary', 'mean'),
Max_Total=('Total_Comp', 'max'),
Headcount=('Country', 'count')
).reset_index()
# 5. Export cleaned data
dept_summary.to_csv("dept_summary.csv", index=False)
print(dept_summary)
2. Core Data Structures & Metadata Inspection
import pandas as pd
# 1. Series (1D labeled array)
s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'], name="Score")
# 2. DataFrame (2D heterogeneous table)
df = pd.DataFrame({
'Country': ['Belgium', 'India', 'Brazil'],
'Capital': ['Brussels', 'New Delhi', 'Brasilia'],
'Population': [11190846, 1303171035, 207847528]
})
# 3. Metadata inspection
df.shape # (3, 3) Tuple of (rows, cols) - property, NOT a method
df.columns # Index of column names
df.index # Row index labels
df.dtypes # Data types per column
df.ndim # 2
df.size # 9 Total cell count
df.info() # Memory usage, dtypes, and non-null summary
df.describe() # Quick summary statistics for numeric columns
3. Data Import & Export (I/O)
| Format | Read Syntax | Write Syntax | Key Parameters |
|---|---|---|---|
| CSV | pd.read_csv('file.csv') |
df.to_csv('out.csv', index=False) |
header=0, sep=',', usecols=['a', 'b'], nrows=1000 |
| Excel | pd.read_excel('file.xlsx') |
df.to_excel('out.xlsx', sheet_name='Sheet1') |
sheet_name=0, skiprows=2 |
| Multi-sheet Excel | xlsx = pd.ExcelFile('file.xlsx')df = pd.read_excel(xlsx, 'Sheet1') |
- | Reuses open file handle for speed |
| SQL Database | pd.read_sql(sql, engine)pd.read_sql_table('table', engine) |
df.to_sql('table', engine, if_exists='append') |
Requires SQLAlchemy engine; chunksize=10000 |
| Parquet | pd.read_parquet('data.parquet') |
df.to_parquet('out.parquet') |
Fast columnar format with schema retention |
| JSON | pd.read_json('file.json') |
df.to_json('out.json', orient='records') |
orient='records' | 'split' | 'index' |
| Clipboard | pd.read_clipboard() |
df.to_clipboard() |
Quick table ingestion from web/Excel copy |
4. Indexing, Slicing & Boolean Filtering
⚠️ Note:
df.ixwas completely removed in Pandas 1.0. Always use explicitlocoriloc.
# 1. Label-based indexing (loc: inclusive of endpoint)
df.loc[0, 'Country'] # Scalar access
df.loc[0:2, ['Country', 'Capital']] # Rows 0 to 2 inclusive, selected columns
df.at[0, 'Country'] # Fast scalar lookup
# 2. Position-based indexing (iloc: half-open interval [start, stop))
df.iloc[0, 1] # Row 0, column 1
df.iloc[0:2, 0:2] # First 2 rows, first 2 columns
df.iat[0, 1] # Fast position scalar lookup
# 3. Column access & slicing
df['Country'] # Returns Series
df[['Country', 'Capital']] # Returns DataFrame
df[1:3] # Slices rows by integer position
# 4. Boolean filtering (combine conditions with &, |, ~ and parentheses)
mask = (df['Population'] > 1e8) & (df['Country'] != 'Brazil')
filtered_df = df[mask]
# 5. Query string filtering (clean readable syntax)
filtered_query = df.query("Population > 1e8 and Country != 'Brazil'")
# 6. Safe conditional assignment (avoids SettingWithCopyWarning)
df.loc[df['Population'] < 1e7, 'Population'] = 0
5. Data Cleaning & Missing Values
# 1. Missingness checks
df.isna() # Boolean missingness matrix
df.isna().sum() # Count of NaNs per column
# 2. Dropping missing values (dropna)
df.dropna(axis=0, how='any') # Drops any row containing NaN
df.dropna(axis=1, how='all') # Drops column only if all entries are NaN
df.dropna(subset=['Country', 'Capital']) # Drops row only if key columns are missing
# 3. Imputation (fillna)
df['Population'] = df['Population'].fillna(df['Population'].median())
df.ffill() # Forward-fill previous valid values
df.bfill() # Backward-fill next valid values
# 4. Deduplication
df.duplicated(subset=['Country'])
df.drop_duplicates(subset=['Country'], keep='first')
# 5. Renaming and casting
df = df.rename(columns={'Population': 'Pop_Count', 'Country': 'Nation'})
df['Pop_Count'] = df['Pop_Count'].astype('int64')
# 6. Vectorized string operations (.str accessor)
df['Capital_Clean'] = df['Capital'].str.strip().str.lower()
df['Has_New'] = df['Capital'].str.contains('New', na=False)
6. Functional Transformations (map & apply)
⚠️ Note:
df.applymap()was removed in Pandas 2.2+. Usedf.map()for element-wise transformations across a DataFrame.
| Method | Target Object | Semantics & Example |
|---|---|---|
s.map() |
Series | Dictionary value replacement or element-wise function: s.map({'a': 1, 'b': 2}) |
df.map() |
DataFrame | Applies function to every individual cell: df.map(lambda x: str(x).upper()) |
df.apply() |
DataFrame | Applies function along an axis (row-wise or column-wise): df.apply(np.mean, axis=0) |
7. Sorting, Ranking & Aggregation
# 1. Sorting
df.sort_values(by=['Country', 'Population'], ascending=[True, False])
df.sort_index(axis=0, ascending=True)
# 2. Ranking ('average', 'min', 'max', 'first', 'dense')
df['Pop_Rank'] = df['Population'].rank(ascending=False, method='min')
# 3. Statistical summaries (pass numeric_only=True to prevent warnings)
df.sum(numeric_only=True)
df.mean(numeric_only=True)
df.median(numeric_only=True)
df.std(numeric_only=True) # Sample standard deviation (ddof=1)
df.quantile(0.75, numeric_only=True)# 75th percentile
df['Population'].idxmax() # Row index of maximum value
# 4. Frequency counts
df['Country'].value_counts(normalize=True, dropna=False)
8. Automatic Alignment & Arithmetic
Pandas automatically aligns on index labels during binary operations; mismatched positions receive NaN:
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['b', 'c', 'd'])
# Direct addition produces NaNs for unmatched keys 'a' and 'd'
s_res = s1 + s2
# Arithmetic method with default fill_value
s_aligned = s1.add(s2, fill_value=0)
# a 1.0 (1 + 0)
# b 6.0 (2 + 4)
# c 8.0 (3 + 5)
# d 6.0 (0 + 6)
9. GroupBy Operations
grouped = df.groupby('Department')
# 1. Single column summary
dept_mean = grouped['Salary'].mean()
# 2. Multi-column, multi-aggregation (.agg)
agg_df = grouped.agg({
'Salary': ['mean', 'median', 'std'],
'Bonus': 'sum',
'Country': 'nunique'
})
# 3. Broadcast group stats to original row shape (.transform)
df['Dept_Avg_Salary'] = grouped['Salary'].transform('mean')
df['Diff_From_Dept_Mean'] = df['Salary'] - df['Dept_Avg_Salary']
# 4. Filter groups (.filter)
large_depts = grouped.filter(lambda group: len(group) >= 5)
10. Merging, Concatenation & Reshaping
⚠️ Note:
DataFrame.append()was removed. Usepd.concat([df1, df2], ignore_index=True).
10.1 Relational Joins (pd.merge)
# SQL-style joins on keys
merged = pd.merge(
left_df, right_df,
on='user_id', # Join key (or left_on='uid', right_on='id')
how='inner', # 'inner', 'left', 'right', 'outer', 'cross'
suffixes=('_left', '_right')
)
10.2 Concatenation (pd.concat)
# Vertical row-wise concatenation
df_vertical = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
# Horizontal column-wise concatenation
df_horizontal = pd.concat([df1, df2], axis=1)
10.3 Pivoting & Melting
# 1. Pivot Table (summary aggregation)
pivot = df.pivot_table(
index='Country',
columns='Department',
values='Salary',
aggfunc='mean',
fill_value=0,
margins=True # Adds total summary row/column
)
# 2. Unpivot Wide to Long (melt)
wide_df = pd.DataFrame({'Date': ['2026-01-01'], 'Store_A': [100], 'Store_B': [150]})
long_df = pd.melt(
wide_df,
id_vars=['Date'],
value_vars=['Store_A', 'Store_B'],
var_name='Store',
value_name='Sales'
)
11. Time Series Handling
# 1. Datetime conversion
df['timestamp'] = pd.to_datetime(df['date_str'], format='%Y-%m-%d %H:%M:%S')
df = df.set_index('timestamp')
# 2. Component extraction (.dt accessor)
df['year'] = df['timestamp'].dt.year
df['month'] = df['timestamp'].dt.month
df['weekday_name'] = df['timestamp'].dt.day_name()
# 3. Resampling frequencies
monthly_sales = df['sales'].resample('ME').sum() # 'ME' month-end, 'W' weekly, 'D' daily
# 4. Rolling window calculations
df['7D_Moving_Avg'] = df['sales'].rolling(window=7).mean()