Series & DataFrames
pandas is Python's main library for working with tables of data. It has two core structures: the Series, a single labelled column, and the DataFrame, a whole table made of Series that share the same row labels.
The Series
A Series is a one-dimensional array of values with an index: a label for every value. If you don't give labels, pandas numbers the rows from 0.
import pandas as pd
prices = pd.Series([180, 160, 350],
index=["Maize flour", "Sugar", "Cooking oil"],
name="price")
print(prices)
print(prices["Sugar"])
The labels are on the left, the values on the right, and the last line shows the Series' name and data type. A Series behaves like a mix of a NumPy array (fast maths) and a dictionary (lookup by label). You can even create one from a dictionary: pd.Series({"Sugar": 160, "Rice": 220}).
print(prices * 2) # maths works on every value print(prices.mean())
The DataFrame
A DataFrame is a table with rows and named columns. The easiest way to make one is from a dictionary whose keys are column names and whose values are lists. We'll use this small shop dataset across the pandas pages.
sales = pd.DataFrame({
"product": ["Maize flour", "Sugar", "Cooking oil", "Rice", "Sugar"],
"county": ["Nairobi", "Kisumu", "Nairobi", "Nakuru", "Nairobi"],
"units": [30, 12, 8, 15, 20],
"price": [180, 160, 350, 220, 160],
})
print(sales)
Each column is a Series, and all of them share the index 0 to 4 on the left.
units, gives a Series that keeps the same index.Inspecting a DataFrame
print(sales.shape) # (rows, columns) print(sales.columns) print(sales.dtypes)
Text columns show the dtype object in pandas 2.x (pandas 3.0 and later show a dedicated string type, str, instead). Other first-look tools are sales.head(n) for the first n rows, sales.tail(n) for the last n, sales.info() for a summary of columns and missing values, and sales.describe() for summary statistics.
Selecting columns
Use square brackets with a column name to get one column as a Series, or a list of names to get a smaller DataFrame.
print(sales["units"].sum()) print(sales[["product", "units"]].head(2))
Note the double brackets: the outer pair means "select", the inner pair is a Python list of column names.
Selecting rows with loc and iloc
| Accessor | Selects by | Example |
|---|---|---|
.loc[] | Labels (index labels and column names); slices include the end | sales.loc[0, "product"] |
.iloc[] | Integer positions, like NumPy; slices exclude the end | sales.iloc[0, 0] |
print(sales.loc[2, "product"]) # row label 2, column "product" print(sales.loc[0]) # the whole first row, as a Series print(sales.iloc[1:3, [0, 2]]) # rows at positions 1-2, columns 0 and 2
The row comes back as a Series whose dtype is object, because it mixes text and numbers. With the default 0, 1, 2… index, labels and positions look the same, but after sorting or filtering they differ, so choose deliberately: loc for labels, iloc for positions.
Adding a column
Assign to a new column name. Column maths is vectorised, just like NumPy.
sales["revenue"] = sales["units"] * sales["price"] print(sales[["product", "revenue"]])
sales.revenue (dot access) works for reading simple column names, but it fails for names with spaces and can clash with DataFrame methods (a column called count or size). To create a column you must use brackets: sales["revenue"] = .... Using brackets everywhere is the safe habit.
Key points
- A Series is one labelled column; a DataFrame is a table of Series sharing an index.
- Build DataFrames from a dictionary of lists, then inspect them with
shape,dtypes,head()andinfo(). df["col"]gives a Series;df[["a", "b"]]gives a DataFrame.locselects by label,ilocby position.
Tip: use the ← and → keys to move between pages.
