Intermediate   Chapter 184 · 40 min read · Module 14: Advanced Application Development

Introduction to Pandas

Learning objectives
  • 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.

DataFrame: a two-dimensional table in Pandas with labelled rows (the index) and labelled columns. Each column is a Series.
Series: a one-dimensional labelled array. A single column of a DataFrame is a Series.

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.

Example 1: a Series with custom labels
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())
tea 40 milk 25 rice 60 dtype: int64 25 125 rice

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().

Example 2: build a DataFrame and inspect it
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())
name age city score 0 Asha 21 Pune 88 1 Ravi 25 Delhi 72 2 Meena 22 Pune 95 3 John 30 Goa 60 (4, 4) ['name', 'age', 'city', 'score'] 78.75

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.

SelectorUsesExampleMeaning
df["score"]column namedf["score"]one column as a Series
df.loc[1]row labeldf.loc[1, "name"]value at row label 1, column name
df.iloc[0]positiondf.iloc[0:2]first two rows by position
df[mask]boolean Seriesdf[df["age"] > 21]rows where the test is True
Example 3: filter, sort and add a column
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())
name age score passed 1 Ravi 25 72 True 2 Meena 22 95 True 3 John 30 60 False ['Meena', 'Asha', 'Ravi', 'John'] Ravi ['Asha', 'Ravi']

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.

Example 4: handle missing values
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())
2 30.0 [10.0, 0.0, 30.0, 0.0, 50.0] [10.0, 30.0, 50.0]

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.

Example 5: groupby and value_counts
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())
city Delhi 76.0 Goa 60.0 Pune 91.5 Name: score, dtype: float64 {'Pune': 2, 'Delhi': 2, 'Goa': 1}

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.

Example 6: write a CSV and read it back
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())
item qty 0 pen 10 1 book 3 13
Pandas 3 changed some defaults, such as the way text columns are stored and the copy-on-write rule: changing a selected piece never changes the original table behind your back. Write your code so that it does not depend on that old behaviour. Assign results back explicitly, for example df["x"] = ....

Python syntax

Syntax
import pandas as pd
df = pd.DataFrame({"col1": [..], "col2": [..]})
Syntax
df["col"]            # one column
df.loc[row_label, "col"]
df.iloc[row_position]
Syntax
df[df["col"] > value]  # filter rows
Syntax
df.groupby("key")["col"].mean()
Syntax
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

Mistake: Using and / or to combine masks, as in df[(a > 1) and (b < 5)].
Fix: Use &, | and ~ and put each condition in parentheses.
Mistake: Mixing up 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.
Mistake: Looping over rows with a for loop to compute a column.
Fix: Use vectorised column operations such as df["a"] * df["b"], which are shorter and much faster.
Mistake: Forgetting that to_csv writes the index as an extra column.
Fix: Pass index=False unless you really want the row labels saved.
Mistake: Ignoring NaN values before computing results.
Fix: Check df.isna().sum() first, then choose to drop or fill the gaps.

Important tips

  • Start every analysis with df.shape, df.head() and df.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, loc selects by label, iloc by position.
  • Boolean masks filter rows; combine them with &, | and ~.
  • Missing numbers are NaN; use isna, fillna and dropna.
  • groupby splits, applies and combines to summarise groups.
  • read_csv and to_csv move 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) versus iloc (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 pd
  • pd.DataFrame(dict_of_lists) makes a table
  • df["col"] is a Series; df[["a","b"]] is a DataFrame
  • df[df["x"] > 5] filters rows
  • df.groupby("k")["v"].sum() totals per group
  • isna, fillna, dropna handle gaps
  • read_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

Related chapters