Beginner: data foundations · Cleaning, exploring and visualising data · topic 17 of 62 · 35 min
pandas basics: Series and DataFrames
Explanation
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.
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 58First look at any dataset
| Command | What 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
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 columnsSorting and new columns
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 columnsReading 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.
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 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.
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])Practice (0/2 done)
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Cleaning messy dataCleaning, exploring and visualising data · same module
- Grouping, joining and reshapingCleaning, exploring and visualising data · same module
- CSV files and simple statisticsPython Programming · Working with data
- What Python is used for: web, data and AIPython Programming · Python in the real world
- SELECT and WHERE: finding rowsBackend Development · Databases and SQL basics
- What is a database?Backend Development · Databases and SQL basics
Questions people ask about this
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.
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"].
Which package is mainly used to work with tables of data?Related
Answer: pandas
pandas gives you the DataFrame, a table with named columns.
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.
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
- 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.
- Module 4 exam: Cleaning, exploring and visualising data · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, The ML workflow, regression and classification. 62 topics left in the course before the final exam.