Skip to content

Pandas Tutorial for Beginners: Learn the Core With One Dataset

Quick answer

Learn pandas through one small marks table: selection, filtering, missing values, groupby and merge, with outputs shown and common mistakes explained.

Pandas Tutorial for Beginners: Learn the Core With One Dataset

This pandas tutorial teaches the core of the library through one small table of student marks: creating a DataFrame, selecting rows and columns with loc and iloc, filtering, fixing missing values, grouping, and merging two tables. pandas is a core Python library for tabular data, and these operations cover most everyday analysis work.

Key takeaways

  • pandas has two structures to learn: a Series (one labelled column) and a DataFrame (a table of Series that share an index).
  • loc selects by label and includes both ends of a slice. iloc selects by position and excludes the end, like normal Python.
  • If you know SQL or Excel, you already know the ideas. The table below maps them to pandas methods.
  • pandas 3.0, released in January 2026, changed two behaviours beginners meet early: text columns show as str, and chained assignment no longer updates the original table.

On this page:

How does pandas map to SQL and Excel?

Almost every pandas operation has a twin you may already use. Keep this table open while you practise.

TaskExcelSQLpandas
Open a fileFile, OpenFROM tablepd.read_csv("file.csv")
Pick columnsHide other columnsSELECT a, bdf[["a", "b"]]
Filter rowsFilter dropdownWHERE a > 60df[df["a"] > 60]
SortSort buttonORDER BY a DESCdf.sort_values("a", ascending=False)
Summarise by groupPivot tableGROUP BYdf.groupby("g")["a"].mean()
Look up from another tableVLOOKUP / XLOOKUPLEFT JOINdf.merge(other, on="key", how="left")
Count valuesCOUNTIFCOUNT(*) GROUP BYdf["g"].value_counts()

What are Series and DataFrame?

A Series is a single labelled column of one data type, and a DataFrame is a two-dimensional table whose columns can each have a different type. The pandas package overview lists them as the library's two primary data structures.

Install pandas with pip install pandas, then create the table used through the rest of this tutorial. The marks are illustrative.

import pandas as pd

marks = pd.DataFrame({
    "roll": [1, 2, 3, 4, 5],
    "name": ["Asha", "Bilal", "Chitra", "Dev", "Esha"],
    "section": ["A", "A", "B", "B", "A"],
    "maths": [78, 45, 91, None, 66],
    "physics": [69, 52, 88, 74, None],
})

print(marks.shape)     # (5, 5): five rows, five columns
print(marks.head(2))   # first two rows
print(marks.dtypes)    # type of each column

Two things to notice in the output. First, maths and physics are float64 even though you typed whole numbers, because a missing value forces the column to a floating-point type. Second, name and section show as str on pandas 3 and as object on older versions. The pandas 3.0 release notes explain that a dedicated string data type is enabled by default from that version.

One column of the table is a Series:

print(marks["maths"].mean())   # 70.0, missing value is skipped

How do you select and filter data?

Use loc when you think in labels and conditions, and iloc when you think in positions. The official 10 minutes to pandas guide recommends these optimised access methods and points out that for label slicing both endpoints are included.

# rows where maths is above 60, only two columns
print(marks.loc[marks["maths"] > 60, ["name", "maths"]])
#      name  maths
# 0    Asha   78.0
# 2  Chitra   91.0
# 4    Esha   66.0

# first two rows, columns at positions 1 and 2
print(marks.iloc[0:2, 1:3])
#     name section
# 0   Asha       A
# 1  Bilal       A

The slice trap

marks.loc[0:1] returns rows labelled 0 and 1, two rows. marks.iloc[0:1] returns only the row at position 0. Same numbers, different rules. This catches almost every beginner once.

Combining conditions

Wrap each condition in brackets and use & for and, | for or. Python's and and or keywords do not work on columns.

print(marks[(marks["section"] == "A") & (marks["maths"] > 60)][["name", "maths"]])
#    name  maths
# 0  Asha   78.0
# 4  Esha   66.0

How do you handle missing values?

Count them first, then decide column by column whether to fill, drop or investigate. pandas shows a missing number as NaN and leaves it out of calculations such as mean() by default.

print(marks.isna().sum())      # maths 1, physics 1

marks["maths"] = marks["maths"].fillna(0)                           # Dev was absent: school rule says 0
marks["physics"] = marks["physics"].fillna(marks["physics"].mean()) # Esha: fill with class mean, 70.75
marks["total"] = marks["maths"] + marks["physics"]
print(marks[["name", "maths", "physics", "total"]])

The two fills above encode two different decisions. Zero for an absent student and a class mean for a lost answer sheet give very different totals, and neither is "the pandas way". The rule comes from the people who own the data. Write the reason as a comment, as shown. For a wider set of methods, see data cleaning techniques across Excel, SQL and Python.

How does groupby work?

It splits the rows into groups, applies a calculation to each group and combines the results into a new table. The pandas group by guide describes exactly these three steps and compares the operation to SQL's GROUP BY.

print(marks.groupby("section")["total"].agg(["mean", "max"]))
#                mean    max
# section
# A        126.916667  147.0
# B        126.500000  179.0

Read the trace: section A has Asha (147), Bilal (97) and Esha (136.75), mean 126.92. Section B has Chitra (179) and Dev (74), mean 126.5. The sections look equal on the mean, yet B contains both the topper and the student who scored zero in maths. That is why you ask for more than one statistic.

If you are comfortable with SQL, compare this with SQL window functions, which solve similar per-group problems.

How do you combine two tables?

Use merge with a shared key column and choose the join type deliberately. A left join keeps every row of the first table, which is usually what you want when adding lookup information.

hostel = pd.DataFrame({"roll": [1, 2, 3, 6],
                       "hostel": ["Ganga", "Kaveri", "Ganga", "Narmada"]})

print(marks.merge(hostel, on="roll", how="left")[["roll", "name", "hostel"]])
#    roll    name  hostel
# 0     1    Asha   Ganga
# 1     2   Bilal  Kaveri
# 2     3  Chitra   Ganga
# 3     4     Dev     NaN
# 4     5    Esha     NaN

Dev and Esha have no hostel record, so they get NaN. Roll 6 exists only in the hostel table and is dropped. With how="inner" you would keep only rolls 1 to 3. Always check the row count before and after a merge: a jump in rows means duplicate keys. The logic is the same as in SQL joins.

Which beginner mistakes should you avoid?

Four mistakes cause most early frustration, and each has a simple fix.

  1. Chained assignment. marks["maths"][marks["roll"] == 2] = 54 does not change marks. The pandas 3.0 release notes state that chained assignment "will stop working". Write it in one step: marks.loc[marks["roll"] == 2, "maths"] = 54.
  2. Forgetting to assign back. Most methods return a new object. marks.sort_values("total") alone changes nothing you keep. Write marks = marks.sort_values("total").
  3. Looping over rows. If you are writing for loops over a DataFrame, look for a column operation. marks["maths"] + marks["physics"] is shorter and faster than a loop.
  4. Trusting types. A numeric column read as text will sort "100" before "20". Check dtypes after every file load.

Once these feel natural, practise on real files. The guide to Python for data analysis shows the full workflow, and the NumPy tutorial explains the arrays underneath pandas.

Next step: export the table with marks.to_csv("marks_clean.csv", index=False), then repeat every step on a CSV of your own. For a structured course in data analytics, the Certification Program in Data Analytics with AI and Gen AI from E&ICT Academy, IIT Roorkee runs for 06 months.

Frequently asked questions

What is pandas used for in Python?

pandas is used to load, clean, reshape, summarise and export tabular data such as CSV files, Excel sheets and database query results. Analysts use it for reporting and exploration, and data scientists use it to prepare data before modelling.

What is the difference between loc and iloc in pandas?

loc selects rows and columns by label or by a boolean condition, and a label slice includes both endpoints. iloc selects by integer position and excludes the end of a slice, like standard Python indexing.

How long does it take to learn pandas?

It varies by person. The core operations in this tutorial can be practised in a few focused sessions, but fluency comes from using pandas on several real datasets. Aim to complete two or three small analyses instead of counting days.

Is pandas enough for a data analyst job?

No single tool is. Analyst roles commonly expect SQL, a spreadsheet tool and a dashboard tool alongside Python. pandas is the Python part of that set, and it is most convincing when shown inside a finished project.

Why does my pandas column show object or str as its type?

Both mean the column holds text. Older pandas versions display text columns as object. From pandas 3.0, a dedicated string type is the default and displays as str. If a numeric column shows either type, it contains non-numeric values that need cleaning.

Share LinkedIn X WhatsApp
×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.