Lesson 4: Exploring Data With pandas
pandas is the Python library that turns a table of data into something you can explore with a few lines of code. Its central object is the DataFrame: a table with named columns and labelled rows, much like a spreadsheet, but programmable. Once data is in a DataFrame, you can select columns, filter rows, group by a category, and summarise a whole column in a single line — the operations that make up most of exploratory analysis.
Exploration starts with simple questions. How many rows and columns are there? What are the column names and types? What does the first handful of rows look like? The code below answers all of those, then goes further: describe() gives the count, mean, spread and quartiles of every number column, and value_counts() counts how often each category appears. These two commands alone will tell you more about a new dataset than an hour of staring at the raw file.
import pandas as pd
df = pd.read_csv("survey.csv")
print(df.shape)
print(df.dtypes)
print(df.head())
print(df.describe())
print(df["year_group"].value_counts())
Selecting, Filtering and Grouping
Three operations do most of the work. Selecting picks out a column — df["score"] — or a set of columns. Filtering keeps only the rows that meet a condition, such as df[df["score"] > 80], which returns the rows where the score is above 80. Grouping splits the table by a category and summarises each group, for example the average score for each year group: df.groupby("year_group")["score"].mean(). That one line answers a question that would take many steps in a spreadsheet, and it is the pattern behind most of the analysis in this course.
Filtering has a subtlety worth learning early: comparisons in pandas use == for equals and combine with & for "and", and each condition needs brackets. Writing df[(df["year_group"] == 10) & (df["score"] > 80)] is the correct form. The brackets look fussy, but they are the price of a clear rule: pandas needs to know exactly which rows each condition refers to before it combines them.
Exploring Before Analysing
Exploration is not the analysis itself; it is the step that makes the analysis safe. It is where you find the missing values, the mislabelled categories, the column that is actually text pretending to be numbers. A good habit is to explore first and write down three things: what the data contains, what is wrong with it, and what question it can answer. Only then should you move on to charts and tests. The analyst who explores first rarely has to redo their work; the one who jumps to conclusions usually does.
Thinking in Tables
Working with DataFrames rewards a particular way of thinking: think in whole columns, not in single values. A beginner's instinct is to loop through rows one at a time, checking each value and deciding what to do — the way a person would work through a spreadsheet by hand. pandas is designed for the opposite: you describe an operation on a whole column, and it applies it to every row at once. Filtering, grouping and summarising are all column operations, and they are both faster to write and faster to run than a loop. When you catch yourself writing a loop over rows, stop and ask whether a column operation does the same thing — it almost always does.
This way of thinking also makes your analysis easier to read. A line that says "group by year group and take the mean score" states the intention directly, while a loop that accumulates totals in a dictionary hides it. Code that states its intention is code that can be checked, and code that can be checked is code you can trust. The habit of thinking in tables is one of the most transferable skills in this course: it applies to spreadsheets, databases, and every data tool you will meet next.
Debugging pandas Code
pandas errors are famously cryptic, so learn the three you will meet most. A KeyError means you asked for a column that does not exist — usually a typo, or a column name with a hidden space. Check the exact names with df.columns before anything else. A SettingWithCopyWarning means you tried to change a filtered copy of a table and pandas is unsure whether you meant the copy or the original; the safe fix is to make an explicit copy with .copy() before changing it. And a merge that suddenly doubles your rows usually means the key you joined on was not unique — check for duplicates in the key column on both sides before merging.
The general debugging habit is the same as in any programming: reproduce the problem on a tiny piece of data, print the shape of the table after each step, and check that each step did what you expected before moving on. A table that loses half its rows after a filter, or gains rows after a merge, is telling you something, and the shape printed after each step is the evidence. Analysts who print shapes as they go find their errors in minutes; those who run a whole script and only check the end spend hours.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Data Analysis with Python and Pandas Tutorial Introduction — sentdex
sentdex introduces pandas as a high-performance data analysis library, and shows a first DataFrame in action.
Key Terms
- pandas
- A Python library for working with tables of data.
- DataFrame
- pandas' table object: named columns, labelled rows, like a programmable spreadsheet.
- Series
- One column of a DataFrame, with its own index.
- Filtering
- Keeping only the rows that meet a condition.
- Grouping
- Splitting a table by a category and summarising each group.
- describe()
- A pandas method that summarises every number column: count, mean, spread and quartiles.
Discussion Questions
- Why is exploration a separate step from analysis, rather than part of it?
- A column contains the values '10', '11' and 'twelve'. What problems will that cause, and how would you fix them?
- When would grouping by a category mislead you, even if the code is correct?
Practice Questions
- What is a DataFrame?
- What does
df.describe()show? - Write the pandas code to find the average score for each year group.
- What does
df[df["score"] > 80]return? - What does
df["year_group"].value_counts()tell you?
Show answers
- A pandas table: named columns and labelled rows, like a programmable spreadsheet. Most pandas work happens on DataFrames.
- A summary of every number column: how many values, the mean, the spread, and the quartiles.
df.groupby("year_group")["score"].mean()— group the rows by year group, take the score column, and average each group.- Only the rows where the score is above 80. It filters the table to the rows meeting the condition.
- How many rows fall into each year group. It counts how often each category appears.