Intermediate Chapter 184 · 40 min read · Module 14: Advanced Application Development
Introduction to Pandas
- After this chapter you can explain what a Series and a DataFrame are.
- You can create a DataFrame from a dictionary and inspect it with shape, columns and head.
- You can select columns and rows with [], loc and iloc and filter rows with boolean masks.
- You can add columns, sort values and deal with missing data using isna, fillna and dropna.
- You can summarise data with groupby and value_counts and read or write CSV files.
Almost every data task starts with a table: sales by month, marks of students, readings from a sensor. Doing this work with plain lists and dictionaries is slow to write and easy to get wrong. Pandas gives Python a proper table type with named columns and a large toolbox for cleaning and summarising data.
In this chapter you will meet the two main Pandas types, the Series and the DataFrame. You will learn to select and filter data, add new columns, deal with missing values, group rows to compute averages, and move data in and out of CSV files. These skills are the base of data analysis and machine learning work in Python.
Pandas works closely with NumPy, which you met in the previous chapter. If you are comfortable with arrays and vectorised operations, you will find that a column of a DataFrame behaves in much the same way.
Why Pandas?
Real data usually comes as a table: rows of records and columns of facts, like a spreadsheet or a database table. Pandas is the most popular Python library for working with such tables. It is built on top of NumPy, so it is fast, and it gives you friendly names for rows and columns, tools for missing values, and one-line commands for sorting, filtering, grouping and summarising. Pandas is a third-party package. Install it once with pip install pandas and import it with the usual short name pd.
Series: a labelled column of values
A Series holds values of one type together with an index of labels. If you do not give labels, Pandas uses 0, 1, 2 and so on. Arithmetic on a Series is vectorised: s * 2 doubles every value without a loop. Methods such as sum(), mean(), max() and idxmax() summarise the data.
import pandas as pd
prices = pd.Series([40, 25, 60], index=["tea", "milk", "rice"])
print(prices)
print(prices["milk"])
print(prices.sum())
print(prices.idxmax())Creating a DataFrame
The easiest way to build a DataFrame is from a dictionary where each key is a column name and each value is a list of that column's data. All lists must have the same length. You can also read a table from a file with pd.read_csv("file.csv"), which is how most real projects start. Useful first checks are df.shape (rows and columns), df.head() (first rows), df.columns and df.info().
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi", "Meena", "John"],
"age": [21, 25, 22, 30],
"city": ["Pune", "Delhi", "Pune", "Goa"],
"score": [88, 72, 95, 60],
})
print(df)
print(df.shape)
print(list(df.columns))
print(df["score"].mean())Selecting rows and columns
Use df["col"] to get one column as a Series, and df[["a", "b"]] (a list inside the brackets) to get several columns as a new DataFrame. For rows, Pandas has two selectors that beginners often mix up. loc selects by label, and its slices include the end label. iloc selects by integer position, and its slices exclude the end, like normal Python.
| Selector | Uses | Example | Meaning |
|---|---|---|---|
| df["score"] | column name | df["score"] | one column as a Series |
| df.loc[1] | row label | df.loc[1, "name"] | value at row label 1, column name |
| df.iloc[0] | position | df.iloc[0:2] | first two rows by position |
| df[mask] | boolean Series | df[df["age"] > 21] | rows where the test is True |
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi", "Meena", "John"],
"age": [21, 25, 22, 30],
"score": [88, 72, 95, 60],
})
df["passed"] = df["score"] >= 70
print(df[df["age"] > 21])
print(df.sort_values("score", ascending=False)["name"].tolist())
print(df.loc[1, "name"])
print(df.iloc[0:2]["name"].tolist())Filtering uses a boolean Series called a mask. The expression df["age"] > 21 makes a column of True and False values, and putting it inside df[...] keeps only the True rows. To combine tests use & for and, | for or, and ~ for not, and wrap each test in parentheses, for example df[(df["age"] > 21) & (df["score"] > 70)]. The words and and or do not work on whole columns.
Missing data
Real tables have gaps. Pandas marks a missing number as NaN (not a number). isna() shows where values are missing, dropna() removes rows that contain gaps, and fillna(value) replaces them. Most summary methods such as mean() skip NaN by default, which is usually what you want, but you should always know how many values are missing before trusting an average.
import pandas as pd
import numpy as np
s = pd.Series([10, np.nan, 30, np.nan, 50])
print(s.isna().sum())
print(s.mean())
print(s.fillna(0).tolist())
print(s.dropna().tolist())Grouping and summarising
The groupby method splits a table into groups that share a value, applies a function to each group, and combines the results. It answers questions such as the average score per city or total sales per month. Call groupby("city"), pick a column, then call an aggregate like mean(), sum(), count() or max(). The result is indexed by the group labels. value_counts() is a quick shortcut to count how often each value appears in one column.
import pandas as pd
df = pd.DataFrame({
"city": ["Pune", "Delhi", "Pune", "Goa", "Delhi"],
"score": [88, 72, 95, 60, 80],
})
print(df.groupby("city")["score"].mean())
print(df["city"].value_counts().to_dict())Reading and writing files
Pandas can read and write many formats. pd.read_csv(path) loads a CSV file into a DataFrame, and df.to_csv(path, index=False) saves it without writing the row numbers as an extra column. There are matching functions for Excel, JSON and SQL. The next example writes a small file and reads it back so you can see the round trip. Because it uses the file system of the machine it runs on, treat it as an illustration.
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book"], "qty": [10, 3]})
df.to_csv("items.csv", index=False)
back = pd.read_csv("items.csv")
print(back)
print(back["qty"].sum())df["x"] = ....Python syntax
import pandas as pd
df = pd.DataFrame({"col1": [..], "col2": [..]})df["col"] # one column
df.loc[row_label, "col"]
df.iloc[row_position]df[df["col"] > value] # filter rowsdf.groupby("key")["col"].mean()df = pd.read_csv("file.csv")
df.to_csv("out.csv", index=False)Real-world applications
- Cleaning and analysing survey, sales or marks data.
- Preparing data before training a machine learning model.
- Combining data from CSV, Excel and database sources into one table.
- Making quick reports such as totals and averages per group.
- Time series work such as daily temperatures or stock prices.
Common mistakes
and / or to combine masks, as in df[(a > 1) and (b < 5)].Fix: Use
&, | and ~ and put each condition in parentheses.loc and iloc, so a slice returns one row more or fewer than expected.Fix:
loc uses labels and includes the end label; iloc uses positions and excludes the end.Fix: Use vectorised column operations such as
df["a"] * df["b"], which are shorter and much faster.to_csv writes the index as an extra column.Fix: Pass
index=False unless you really want the row labels saved.Fix: Check
df.isna().sum() first, then choose to drop or fill the gaps.Important tips
- Start every analysis with
df.shape,df.head()anddf.info(). - Use clear column names without spaces so you can also write
df.col. - Chain small steps and print the result of each one while you learn.
- Use
value_counts()to quickly see what values a column holds.
Key points summary
- A DataFrame is a table; each column is a Series.
[]selects columns,locselects by label,ilocby position.- Boolean masks filter rows; combine them with
&,|and~. - Missing numbers are NaN; use
isna,fillnaanddropna. groupbysplits, applies and combines to summarise groups.read_csvandto_csvmove data in and out of files.
Exam and interview points
- Know that DataFrame columns are Series and the index labels rows.
- Explain
loc(label, end included) versusiloc(position, end excluded). - Write a boolean-mask filter with two conditions using
&. - Describe what
groupby(...).mean()returns. - State how
mean()treats NaN by default (it skips it).
Quick revision
import pandas as pdpd.DataFrame(dict_of_lists)makes a tabledf["col"]is a Series;df[["a","b"]]is a DataFramedf[df["x"] > 5]filters rowsdf.groupby("k")["v"].sum()totals per groupisna,fillna,dropnahandle gapsread_csv/to_csv(index=False)
Frequently asked questions
What is the difference between a Series and a DataFrame?
A Series is one labelled column of values. A DataFrame is a table made of several Series that share the same row index.
Should I use Pandas or plain Python lists?
For small, simple data, lists are fine. When you have tables with many rows, missing values, or need grouping and sorting, Pandas is far shorter and faster.
Does Pandas change my original DataFrame when I call sort_values or dropna?
No. Most methods return a new DataFrame. You must assign the result, for example `df = df.dropna()`, to keep it.
How do I see the first few rows of a large table?
Call `df.head()` for the first five rows, or `df.head(10)` for ten. `df.tail()` shows the last rows.
Why does my filter raise an error about ambiguous truth value?
You used `and` or `or` on whole columns. Use `&` or `|` with parentheses around each test.
Practise this chapter
26 practice questions Take the chapter quiz