Skip to content

Beginner: data foundations · Cleaning, exploring and visualising data · topic 17 of 62 · 35 min

pandas basics: Series and DataFrames

Explanation

pandas is the Python library for tables. A DataFrame is a table with named columns, and each column is a Series. You read a CSV with pd.read_csv, look at it with head, info and describe, pick rows and columns with filters, loc and iloc, and sort or add columns in one line.

Why pandas?

Most business data comes as tables: sales exports, survey results, bank statements. Excel works for small tables, but it is hard to repeat the same cleaning every week, and it struggles with lakhs of rows. pandas lets you write the steps once in code, run them on any size of file and get the same result every time.

Series and DataFrame

  • A Series is one column of values with labels (the index). Think of it as a smart list.
  • A DataFrame is a whole table: several Series side by side, sharing the same index (row labels).
  • The index is the set of row labels. By default it is 0, 1, 2 and so on.
python
import pandas as pd

df = pd.DataFrame({
    "name": ["Asha", "Ravi", "Priya", "Imran"],
    "city": ["Pune", "Delhi", "Pune", "Mumbai"],
    "marks": [78, 65, 91, 58],
})
print(df)
#     name    city  marks
# 0   Asha    Pune     78
# 1   Ravi   Delhi     65
# 2  Priya    Pune     91
# 3  Imran  Mumbai     58
A DataFrame built from a dictionary of columns. In real work you would use pd.read_csv("students.csv").

First look at any dataset

CommandWhat it tells you
df.head()The first 5 rows, to see what the data looks like
df.shape(rows, columns), here (4, 3)
df.info()Each column's type and how many values are not missing
df.describe()count, mean, std, min, quartiles and max for number columns
df["city"].value_counts()How many rows have each city

Selecting columns and rows

python
df["marks"]                  # one column: a Series
df[["name", "marks"]]        # several columns: a DataFrame (note the double brackets)
df[df["marks"] > 70]         # rows where marks > 70 (a boolean mask, like NumPy)
df.loc[0, "name"]            # by LABEL: row label 0, column "name" -> 'Asha'
df.iloc[0, 0]                # by POSITION: first row, first column -> 'Asha'
df.loc[df["city"] == "Pune", ["name", "marks"]]   # filter rows and pick columns
loc uses labels; iloc uses integer positions. They look the same here only because the index is 0, 1, 2, 3.

Sorting and new columns

python
df.sort_values("marks", ascending=False)        # best marks first
df["passed"] = df["marks"] >= 60                # new column from a rule
df["percent"] = df["marks"] / 100 * 100         # maths on whole columns
Column maths is vectorised, just like NumPy.

Reading and saving files

pd.read_csv("sales.csv") reads a comma-separated file into a DataFrame. Useful options: sep=";" when the file uses semicolons, encoding="utf-8" for Hindi or other non-English text, parse_dates=["order_date"] to read dates as real dates, and usecols=[...] to load only the columns you need from a huge file. pd.read_excel reads .xlsx files (it needs the openpyxl package). When you are done, df.to_csv("clean.csv", index=False) saves the result; index=False stops pandas from writing the row numbers as an extra column.

Tip: Each column in a DataFrame has one type (dtype): int64 for whole numbers, float64 for decimals, object for text, bool for True/False and datetime64 for dates. If a number column shows up as object, some cell contains text such as "1,200" or "N/A". Fixing that is the job of the next topic.
Think of it like this: A DataFrame is like a well-kept attendance register. Each column has a heading (name, roll number, present), each row is one student, and you can quickly say "show me only the students from Pune, sorted by marks" without copying anything by hand.

Common mistakes

  • df["name", "marks"] with single brackets raises a KeyError. Fix: use a list inside: df[["name", "marks"]].
  • Combining filters with and: df[df.marks > 60 and df.city == "Pune"] fails. Fix: (df.marks > 60) & (df.city == "Pune").
  • Chained assignment like df[df.marks > 60]["grade"] = "P" may not change df and shows a warning. Fix: df.loc[df.marks > 60, "grade"] = "P".
  • Forgetting that most methods return a new DataFrame. df.sort_values("marks") does not change df unless you assign it back.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

pandas basics: Series and DataFrames · 1/7

pandas DataFrames

pandas is how Python handles tables. Let us meet the DataFrame.

Prefer a video by a teacher? Find free videos on “pandas tutorial for beginners dataframe loc iloc filtering” on YouTube ↗

In real life: A weekly sales report in five lines

A retail chain's analyst gets a CSV of last week's bills every Monday. Her pandas script reads it, keeps only completed bills, adds a GST column, sorts by amount and saves the top 100 bills for the store managers. What took an hour in a spreadsheet now takes seconds and never forgets a step.

python
bills = [
    {"bill": 1, "store": "Pune", "amount": 450, "status": "done"},
    {"bill": 2, "store": "Delhi", "amount": 1200, "status": "void"},
    {"bill": 3, "store": "Pune", "amount": 780, "status": "done"},
]
done = [b for b in bills if b["status"] == "done"]
top = sorted(done, key=lambda b: b["amount"], reverse=True)
print([b["bill"] for b in top])
The same steps in plain Python: filter, sort, select. Shows [3, 1].

Practice (0/2 done)

Task 1 · Code · Python

Rows are dictionaries like {"name": "Asha", "city": "Pune", "marks": 78}. Write top_in_city(rows, city) that returns the NAMES of students from that city, sorted by marks from highest to lowest (like df.loc[df.city == city].sort_values("marks", ascending=False)["name"]). If two students have the same marks, keep their original order.

Task 2 · Code · Python

Write describe(values) like a tiny df.describe() for one column: return a dict with "count", "mean", "min" and "max". Round the mean to 2 decimal places. For an empty list return {"count": 0, "mean": None, "min": None, "max": None}.

Quick quiz

Question 1

1.What is a pandas DataFrame?

Question 2

2.Which line selects two columns, name and marks?

Question 3

3.What is the difference between loc and iloc?

Question 4

4.You just loaded a new CSV. Which command shows each column's type and how many values are missing?

Question 5

5.After df.sort_values("marks"), df is still unsorted. Why?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is a pandas DataFrame?

Answer: A table of named columns that share row labels

A DataFrame is a table; each column is a Series.

Which line selects two columns, name and marks?

Answer: df[["name", "marks"]]

Pass a list of column names inside the brackets.

What is the difference between loc and iloc?

Answer: loc selects by label; iloc selects by integer position

With a custom index (like roll numbers) the two give different rows.

You just loaded a new CSV. Which command shows each column's type and how many values are missing?

Answer: df.info()

info() lists dtypes and non-null counts.

After df.sort_values("marks"), df is still unsorted. Why?

Answer: The method returns a new DataFrame; you must assign it back

Write df = df.sort_values("marks") to keep the result.

A CSV row is read with csv.DictReader. What type is r["qty"] for the value 5?Related

Answer: str

The csv module never converts types. Every value is a string until you convert it.

From Reading CSV and JSON with the standard library

What does csv.DictReader give you for each row?Related

Answer: A dict with the header names as keys

DictReader uses the header row as keys, so you can write row["marks"].

From CSV files and simple statistics

Which package is mainly used to work with tables of data?Related

Answer: pandas

pandas gives you the DataFrame, a table with named columns.

From What Python is used for: web, data and AI

What does SELECT name FROM students WHERE marks > 80 return?Related

Answer: Names of students with marks above 80

SELECT name picks one column; WHERE marks > 80 keeps only the rows with more than 80.

From SELECT and WHERE: finding rows

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Cleaning, exploring and visualising data” before its exam: Cleaning messy data, Grouping, joining and reshaping, Exploratory data analysis (EDA), Visualising data honestly.
  2. Module 4 exam: Cleaning, exploring and visualising data · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
  3. Then the next module, The ML workflow, regression and classification. 62 topics left in the course before the final exam.

← Previous: NumPy: fast arrays of numbers