Pandas Cheat Sheet for Beginners: 30 Commands You’ll Use Weekly
Updated on February 18, 2026 10 minutes read
If you’re learning Python for data analysis, pandas is the library that turns messy files into clear answers. It can feel confusing at first because there are many ways to do similar tasks.
This guide is a pandas cheat sheet built for beginners who want the essentials that show up again and again. Think of it as your weekly toolkit for cleaning, filtering, summarizing, and combining DataFrames.
You don’t need to memorize everything to become confident. You just need a reliable set of commands you can reach for, practice, and apply to real datasets.
How to use this cheat sheet (so it actually sticks)
First, skim the command list so you know what’s available when you get stuck. Then practice the same workflow repeatedly: load → inspect → clean → transform → summarize → export.
That repetition matters more than “covering everything.” Most real analytics work is the same handful of moves applied to different datasets.
If you’re aiming for a career change into data, mastering these patterns is a big win. It helps you move from copy-pasting snippets to writing clean, explainable analysis.
Sample dataset used in examples
Most examples assume a DataFrame named df. You can create a small one like this to practice quickly.
import pandas as pd
df = pd.DataFrame({
"customer_id": [101, 102, 103, 104],
"plan": ["Basic", "Pro", "Basic", "Pro"],
"monthly_fee": [29, 59, 29, 59],
"signup_date": ["2025-11-02", "2025-11-10", "2025-12-01", "2025-12-05"],
"churned": [0, 0, 1, 0]
})
Once you’re comfortable, swap this out with a real dataset. Public CSVs are great practice because they come with missing values, inconsistent labels, and real-world messiness.
The 30 pandas commands you’ll use weekly
These commands are grouped in the order you’ll typically use them. Each one includes a short explanation and a quick example you can copy.
1) Importing pandas and loading files
1. import pandas as pd
This is the standard import style you’ll see in almost every tutorial and project. Using pd keeps your code concise and instantly recognizable.
import pandas as pd
2. pd.read_csv()
Use this to load CSV files into a DataFrame. It’s the most common starting point for analytics, reporting, and portfolio projects.
df = pd.read_csv("subscriptions.csv")
If you have date columns, parsing them early makes grouping and sorting much easier.
df = pd.read_csv("subscriptions.csv", parse_dates=["signup_date"])
3. pd.read_excel()
Excel files are everywhere in business workflows, so this command is practical and worth memorizing. It reads a worksheet into a DataFrame.
df = pd.read_excel("subscriptions.xlsx", sheet_name="Sheet1")
If the file has extra header rows, skip them to avoid messy columns.
df = pd.read_excel("subscriptions.xlsx", skiprows=1)
2) Inspecting your data (the first 60 seconds)
4. df.head()
Before you clean or analyze anything, preview the first rows. This helps you spot issues like unexpected nulls or inconsistent formats.
df.head()
df.head(10)
5. df.shape
This returns the dataset size as (rows, columns). It’s a fast sanity check after filtering, joining, or removing duplicates.
df.shape
Think of it as the “did I accidentally delete half my data?” alarm.
6. df.info()
This shows column names, non-null counts, and types. Many beginner problems are type problems, and info() helps you catch them early.
df.info()
If a numeric column shows up as object, it often means text values are hiding inside.
7. df.describe()
Use this for quick summary stats like mean, min/max, and quartiles. It’s useful for checking ranges and catching outliers before you plot.
df.describe()
If you want summaries for text columns too, include all types.
df.describe(include="all")
8. df['col'].value_counts()
This counts unique values and is perfect for category columns like plan types, countries, or product labels. It helps you spot typos and rare categories fast.
df["plan"].value_counts()
To see proportions rather than counts, normalize it.
df["plan"].value_counts(normalize=True)
3) Sorting, selecting, and filtering rows
9. df.sort_values()
Sorting helps you inspect data more clearly. You’ll often sort by dates, revenue, or scores to confirm your transformations worked.
df.sort_values("monthly_fee")
df.sort_values("signup_date", ascending=False)
Sorting by multiple columns is useful when you want stable ordering.
df.sort_values(["plan", "monthly_fee"], ascending=[True, False])
10. df.loc[]
loc is label-based selection and the safest way to filter rows and select columns. It’s also a strong approach for an assignment without warnings.
df.loc[df["monthly_fee"] > 30, ["customer_id", "plan", "monthly_fee"]]
A helpful pattern is “condition first, columns second,” because your intent stays readable.
11. df.iloc[]
iloc selects by position, which is useful when you want quick slices or when you’re working with unnamed columns. It behaves more like array indexing.
df.iloc[0] # first row
df.iloc[:5, :3] # first 5 rows, first 3 columns
Use it when you care about positions rather than labels.
12. df.query()
query() filters rows using expressions that many beginners find easier to read. It’s especially nice when conditions get long.
df.query("monthly_fee > 30")
df.query("plan == 'Pro' and churned == 0")
If a column has spaces, wrap it in backticks.
df.query("`monthly fee` > 30")
4) Editing columns: rename, create, and remove
13. df.rename()
Clean column names reduce errors and make your analysis easier to explain. Renaming early is a common professional habit.
df = df.rename(columns={"monthly_fee": "monthly_price_usd"})
You can rename multiple columns at once.
df = df.rename(columns={"signup_date": "signup_dt", "customer_id": "id"})
14. df.assign()
assign() adds new columns in a clean way, especially when you want to chain multiple steps. It’s ideal for feature engineering.
A common example is annualizing monthly fees: .
df = df.assign(annual_revenue=df["monthly_fee"] * 12)
You can create multiple derived columns in one go.
df = df.assign(
annual_revenue=df["monthly_fee"] * 12,
is_pro=df["plan"].eq("Pro")
)
15. df.drop()
Drop columns or rows you don’t need. This keeps your dataset focused and reduces confusion in later steps.
df = df.drop(columns=["annual_revenue"])
You can also drop rows by index when cleaning test rows or correcting mistakes.
df = df.drop(index=[0, 1])
5) Missing values and duplicates (real data fundamentals)

16. df.isna()
Missing data is normal, so the first step is to measure it. isna() plus sum() gives a quick report by column.
df.isna().sum()
Once you see which columns have missing values, you can choose a strategy instead of guessing.
17. df.fillna()
Use fillna() when missing values should be replaced rather than removed. This is common for categories (“Unknown”) or numeric values (median/mean).
df["plan"] = df["plan"].fillna("Unknown")
For numeric columns, median often works well when there are outliers.
df["monthly_fee"] = df["monthly_fee"].fillna(df["monthly_fee"].median())
18. df.dropna()
Drop missing values when specific fields are required for the analysis. Dates are a common example because time-based reporting depends on them.
df = df.dropna(subset=["signup_date"])
Dropping every row with any missing value is usually too aggressive. Use subset= when possible.
19. df.drop_duplicates()
Duplicates can quietly distort your metrics, especially counts and sums. Removing them is a quick way to make your KPIs more trustworthy.
df = df.drop_duplicates()
If customers appear once, dedupe by customer ID.
df = df.drop_duplicates(subset=["customer_id"], keep="last")
6) Data types and cleaning text
20. df.astype()
Type conversion prevents errors and makes calculations behave correctly. A column like churned should be numeric, not text.
df["churned"] = df["churned"].astype(int)
You can convert multiple columns in one call for a consistent schema.
df = df.astype({"monthly_fee": "float", "churned": "int"})
21. df['col'].str...
Text columns often need cleanup because of inconsistent capitalization, trailing spaces, or mixed labels. Pandas string methods are fast and readable.
df["plan"] = df["plan"].str.lower().str.strip()
Replacing inconsistent labels is also common in real datasets.
df["plan"] = df["plan"].str.replace("pro plus", "pro", regex=False)
7) Working with dates (critical for reporting)
22. pd.to_datetime()
Dates imported as strings don’t sort or group properly. Converting early saves time and prevents subtle mistakes in time-based analysis.
df["signup_date"] = pd.to_datetime(df["signup_date"])
If you have messy date strings, coercing errors prevents crashes and reveals invalid rows.
df["signup_date"] = pd.to_datetime(df["signup_date"], errors="coerce")
23. df['date'].dt...
Once a column is a datetime, .dt makes it easy to extract parts like month and year. This is essential for monthly dashboards and cohort analysis.
df["signup_month"] = df["signup_date"].dt.month
df["signup_year"] = df["signup_date"].dt.year
For monthly reporting, a Year-Month key is often the cleanest approach.
df["signup_ym"] = df["signup_date"].dt.to_period("M")
8) Grouping and aggregating (turning data into insights)
24. df.groupby()
Grouping lets you calculate metrics per category, like average fee by plan or churn by month. This shows up constantly in analytics tasks.
df.groupby("plan")["monthly_fee"].mean()
You can group by multiple columns for more detailed breakdowns.
df.groupby(["plan", "churned"])["monthly_fee"].mean()
25. .agg()
Aggregation is most useful when you compute multiple metrics at once. For example, churn rate is often defined as .
summary = (
df.groupby("plan")
.agg(
customers=("customer_id", "count"),
avg_fee=("monthly_fee", "mean"),
churn_rate=("churned", "mean")
)
)
This “named aggregation” style is popular because it produces clean, report-ready outputs.
9) Combining DataFrames: joins and stacking
26. df.merge()
Merging is how you join tables in SQL. You’ll use it when customer profiles live in one file and subscriptions or payments live in another.
plans = pd.DataFrame({
"plan": ["Basic", "Pro"],
"support_level": ["email", "priority"]
})
df = df.merge(plans, on="plan", how="left")
A left join is a safe default when you want to keep all rows from your main dataset.
27. pd.concat()
Concatenation stacks DataFrames together, which is common when you receive monthly exports. It’s also helpful when combining training data from multiple sources.
df_all = pd.concat([df_jan, df_feb, df_mar], ignore_index=True)
Concatenating side-by-side using axis=1 exists, but stacking rows is the most common weekly use.
10) Reshaping for analysis, charts, and dashboards
28. df.pivot_table()
Pivot tables create spreadsheet-style summaries. They’re excellent when someone wants a “matrix view” of results by time and category.
A common reporting metric is monthly revenue, often computed as (or sum of transaction amounts).
pivot = df.pivot_table(
index="signup_ym",
columns="plan",
values="monthly_fee",
aggfunc="sum",
fill_value=0
)
This format is easy to export, chart, and share with non-technical stakeholders.
29. df.melt()
Melt converts wide data into a long (“tidy”) format, which is often required for plotting and dashboards. If you ever hear “long vs wide,” this is one of the main tools.
long = pivot.reset_index().melt(
id_vars="signup_ym",
var_name="plan",
value_name="revenue"
)
Long format also makes filtering and grouping more consistent across tools.
11) Exporting your results (so your work can be shared)
30. df.to_csv()
Exporting turns analysis into an output others can use. You’ll export cleaned datasets, summaries, and features for dashboards or reports.
summary.to_csv("plan_summary.csv", index=False)
Using index=False avoids exporting the index as a column unless you specifically want it.
A weekly pandas workflow you can copy (CSV → clean → KPIs)

This mini pipeline combines many of the commands above into a realistic pattern. Practicing this workflow across different datasets will build speed and confidence.
import pandas as pd
df = pd.read_csv("subscriptions.csv")
df = df.rename(columns={"monthly_fee": "monthly_price_usd"})
df["signup_date"] = pd.to_datetime(df["signup_date"], errors="coerce")
df["plan"] = df["plan"].str.lower().str.strip()
df["churned"] = df["churned"].astype(int)
df = df.dropna(subset=["signup_date"])
df = df.drop_duplicates(subset=["customer_id"], keep="last")
df["signup_ym"] = df["signup_date"].dt.to_period("M")
monthly = (
df.groupby(["signup_ym", "plan"])
.agg(
customers=("customer_id", "count"),
revenue=("monthly_price_usd", "sum"),
churn_rate=("churned", "mean")
)
.reset_index()
.sort_values(["signup_ym", "plan"])
)
monthly.to_csv("monthly_kpis.csv", index=False)
If you can explain what each block does and why it’s there, you’re thinking like an analyst. That’s exactly the mindset employers look for in entry-level data roles.
Common beginner mistakes (and quick fixes)
A frequent pain point is SettingWithCopyWarning. It happens when pandas isn’t sure if you’re editing the original DataFrame or a slice, so results can be unpredictable.
A reliable fix is to use .loc when assigning values. It makes your intention explicit and avoids ambiguous chained indexing.
df.loc[df["plan"] == "pro", "monthly_fee"] = 59
Another common issue is treating dates like text. Without conversion, sorting and grouping can become silently incorrect, so converting with pd.to_datetime() early is a strong habit.
Turning this cheat sheet into portfolio projects

Commands matter, but hiring decisions are usually based on projects. A solid portfolio shows you can take raw data, clean it, build metrics, and explain results clearly.
A practical beginner project is a “Subscription KPI Report.” You load data, normalize plan names, compute , calculate churn rates, and export a monthly summary.
This is where structure can accelerate progress. Code Labs Academy bootcamps guide you through job-ready skills, help you build a portfolio through hands-on projects, and provide career support like mentoring, interview prep, and job-search strategy.
If you’re considering next steps, you can explore our bootcamps, talk to an advisor, or download the syllabus to see how projects and career support are organized.
Conclusion: master the core, then repeat it on real data
A good pandas cheat sheet isn’t about learning every function. It’s about mastering the weekly essentials: loading files, inspecting structure, cleaning missing values, transforming columns, grouping metrics, and exporting results.
Practice these 30 commands on one dataset, then apply them to another dataset with different quirks. That repetition is what turns “I watched a tutorial” into “I can do this at work.”
When you’re ready for a career-focused roadmap, explore Code Labs Academy programs to build job-ready skills, create portfolio projects with feedback, and get the career support that helps you move from learning to hiring.