Pandas

A complete Pandas cheatsheet covering

Pandas Basics

TaskCodeDescription
Import pandasimport pandas as pdImport pandas library
Check versionpd.versionGet pandas version
Create Seriespd.Series([1,2,3])1D labeled array
Create DataFramepd.DataFrame({'A':[1,2],'B':[3,4]})2D labeled data
Read CSVpd.read_csv('file.csv')Load CSV file
Read Excelpd.read_excel('file.xlsx')Load Excel file
Write CSVdf.to_csv('file.csv', index=False)Save DataFrame as CSV
Write Exceldf.to_excel('file.xlsx', index=False)Save DataFrame as Excel

Data Inspection

TaskCodeDescription
View top rowsdf.head()First 5 rows
View bottom rowsdf.tail()Last 5 rows
Shape of DataFramedf.shape(rows, columns)
Column namesdf.columnsGet all column names
Index infodf.indexGet row index info
Data typesdf.dtypesData types of columns
Summarydf.info()Summary of DataFrame
Statisticsdf.describe()Descriptive stats
Memory usagedf.memory_usage()Memory used by each column

Selecting Data

TaskCodeDescription
Select columndf['col'] or df.colSelect a single column
Select multiple colsdf[['col1','col2']]Multiple columns
Select by positiondf.iloc[0]Row by index
Select by labeldf.loc[0]Row by label
Slicing rowsdf[2:5]Rows 2–4
Conditional filterdf[df['A'] > 10]Filter rows
Multiple conditionsdf[(df['A']>10) & (df['B']<5)]AND condition
isin filterdf[df['A'].isin([1,2,3])]Match multiple values

⚙️ Data Cleaning

TaskCodeDescription
Check missingdf.isnull()Check NaN
Drop missingdf.dropna()Remove NaN rows
Fill missingdf.fillna(0)Replace NaN
Drop duplicatesdf.drop_duplicates()Remove duplicate rows
Replace valuesdf.replace('old','new')Replace specific value
Rename columnsdf.rename(columns={'old':'new'})Rename columns
Change typedf['col'] = df['col'].astype(int)Change data type
Reset indexdf.reset_index(drop=True)Reset index

Data Operations

TaskCodeDescription
Add new columndf['C'] = df['A'] + df['B']Add or combine
Delete columndf.drop('A', axis=1)Remove column
Apply functiondf['A'].apply(lambda x: x*2)Apply function
Sort by columndf.sort_values('A')Sort by column
Sort by indexdf.sort_index()Sort rows by index
Unique valuesdf['A'].unique()Unique values
Value countsdf['A'].value_counts()Frequency count
Rename indexdf.rename_axis('index_name')Rename index

Grouping & Aggregation

TaskCodeDescription
Group by columndf.groupby('A')Group data
Aggregatedf.groupby('A')['B'].mean()Mean by group
Multiple aggregatesdf.groupby('A').agg({'B':['mean','sum']})Multiple functions
Count per groupdf.groupby('A').size()Count per group
Reset group index.reset_index()Convert group index to column

Merging & Joining

TaskCodeDescription
Merge two DFspd.merge(df1, df2, on='id')SQL-style join
Left joinpd.merge(df1, df2, how='left', on='id')Left join
Right joinpd.merge(df1, df2, how='right', on='id')Right join
Outer joinpd.merge(df1, df2, how='outer', on='id')Union join
Concatenatepd.concat([df1, df2])Stack DataFrames
Join by indexdf1.join(df2)Join on index

Statistics & Math

TaskCodeDescription
Sum of columndf['A'].sum()Sum
Mean of columndf['A'].mean()Average
Mediandf['A'].median()Median
Standard deviationdf['A'].std()Std. deviation
Correlationdf.corr()Correlation matrix
Count non-NAdf.count()Count of valid values

Date & Time

TaskCodeDescription
Convert to datetimepd.to_datetime(df['date'])Convert string to datetime
Extract yeardf['date'].dt.yearYear part
Extract monthdf['date'].dt.monthMonth part
Extract daydf['date'].dt.dayDay part
Filter by datedf[df['date'] > '2024-01-01']Filter
Date rangepd.date_range('2024-01-01', periods=5)Create date range

Input/Output Formats

FormatReadWrite
CSVpd.read_csv('file.csv')df.to_csv('file.csv')
Excelpd.read_excel('file.xlsx')df.to_excel('file.xlsx')
JSONpd.read_json('file.json')df.to_json('file.json')
HTMLpd.read_html('file.html')df.to_html('file.html')
SQLpd.read_sql(query, conn)df.to_sql('table', conn)
Picklepd.read_pickle('file.pkl')df.to_pickle('file.pkl')

Miscellaneous

TaskCodeDescription
Transpose DataFramedf.TFlip rows ↔ columns
Get index of maxdf['A'].idxmax()Index of max value
Get index of mindf['A'].idxmin()Index of min value
Clip valuesdf['A'].clip(lower=0, upper=10)Limit values
Cumulative sumdf['A'].cumsum()Running total
Apply lambda to DFdf.applymap(lambda x: x*2)Apply to all elements