pandas Series and DataFrames
Load data into pandas, inspect it with head, info and describe, and select rows and columns with brackets, loc and iloc without the usual surprises.
Welcome back!
Step 1 of 14Learn
A spreadsheet you can program
pandas gives Python two core structures:
- A Series: one column of values with an index (labels for each row).
- A DataFrame: a table of named columns that share one index. Each column is a Series, and each column has its own dtype.
import pandas as pd
df = pd.DataFrame({
"station": ["Harbor", "Market", "Harbor", "Park"],
"hour": [8, 8, 9, 9],
"bikes_out": [14, 9, 6, 11],
})Most of the time you load data from a file instead:
df = pd.read_csv("rentals.csv") # also: read_excel, read_json, read_parquet, read_sql
df = pd.read_csv("rentals.csv", parse_dates=["start_time"])The first thing to do with any new DataFrame is look at it:
df.shape # (rows, columns), e.g. (1800000, 9)
df.head() # first 5 rows (df.tail() for the last 5)
df.info() # column names, dtypes, non-null counts, memory use
df.describe() # count, mean, std, min, quartiles, max for numeric columns
df.dtypes # the type of each columninfo() is the quickest way to spot problems: a column of numbers stored as object (text) usually means a stray value such as "N/A" or "1,200", and a non-null count lower than the row count reveals missing values.
Step 2 of 14Practice · Match the pairs
Match each pandas call to what it tells you.
Tap an answer, then tap the place where it belongs (or drag it there).
df.shapedf.head()df.info()df.describe()
Step 3 of 14Flashcards
First look at any new DataFrame
Tap a card to flip it.
Step 4 of 14Learn
Selecting columns and rows
To get one column, use brackets with its name; you get a Series. Two sets of brackets, a list of names, give a DataFrame:
df["bikes_out"] # Series
df[["station", "bikes_out"]] # DataFrame with two columns(df.bikes_out also works for simple names, but breaks for names with spaces or names that clash with methods, such as a column called count.)
For rows, pandas has two explicit selectors:
.locselects by label: index labels and column names..ilocselects by integer position, like NumPy.
df.loc[0, "station"] # row with index label 0, column "station"
df.loc[0:2, ["station", "hour"]] # labels 0 through 2 INCLUSIVE
df.iloc[0:2, 0:2] # positions 0 and 1 (end EXCLUDED)
df.iloc[-1] # last rowThe inclusive/exclusive difference is deliberate: label slices include the end because labels aren't always numbers. With a date index, df.loc["2026-03-01":"2026-03-07"] naturally includes the 7th.
When the index is the default 0, 1, 2..., labels and positions look the same, which hides the difference. After filtering or sorting, they stop matching: the first row might have label 5, so df.loc[0] fails or finds a different row than df.iloc[0].
Step 5 of 14Practice · Work it out
A DataFrame has the default index 0, 1, 2, ..., 9. How many rows does df.loc[2:5] return?
Step 6 of 14Practice · What would you do?
What would you do?
After sorting rentals by bikes_out from highest to lowest, Jo wants the single busiest row and writes df_sorted.loc[0]. She gets a row with only 6 bikes out. Why?
Step 7 of 14Learn
The index and dtypes
The index is more than row numbers. You can make a meaningful column the index, which speeds up lookups and makes code read naturally:
stations = pd.DataFrame({
"station": ["Harbor", "Market", "Park"],
"capacity": [30, 24, 18],
}).set_index("station")
stations.loc["Market", "capacity"] # 24Indexes also align data automatically. Adding two Series matches values by label, not by position, and labels missing from either side produce NaN. This is powerful, and occasionally surprising when you expected position-based arithmetic.
Getting dtypes right early saves trouble later:
| dtype | Holds | Watch out for |
|---|---|---|
int64 | whole numbers | can't hold NaN in classic NumPy-backed columns; becomes float64 when values are missing |
float64 | decimals, NaN | rounding in money calculations |
object | text (or mixed) | numbers stored as text won't sum |
bool | True/False | |
datetime64[ns] | timestamps | must be parsed from text first |
category | repeated labels | saves memory for columns like station names |
Converting is explicit: df["hour"].astype(int), pd.to_numeric(df["price"], errors="coerce") (bad values become NaN), and pd.to_datetime(df["start_time"]).
Step 8 of 14Practice · Sort into groups
A data file loads with these column dtypes. Which ones probably need fixing before analysis?
Tap an item, then tap its group (or drag it there).
Step 9 of 14Learn
Reading files: the options that matter
pd.read_csv has dozens of parameters, but a handful solve most real-world loading problems:
sep=";": many European exports use semicolons, because the comma is the decimal separator there. Pair it withdecimal=",".usecols=["station", "hour", "bikes_out"]: load only the columns you need, which saves memory on wide files.dtype={"zip": str}: keep codes like ZIP codes as text, or "02139" becomes the number 2139 and loses its leading zero.parse_dates=["start_time"]: convert timestamp columns while loading.na_values=["N/A", "-"]: treat placeholders as missing.nrows=1000: load a sample first to explore a huge file quickly.encoding="latin-1": for older files that fail with a UnicodeDecodeError under the default UTF-8.
For large or frequently reused data, columnar formats such as Parquet load much faster than CSV and remember each column's type, so df.to_parquet("rentals.parquet") once and pd.read_parquet afterwards is a common speed-up.
When a file "won't load right", open the first few lines in a text editor. Seeing the real separator, header row, quoting and date format usually tells you which option you need.
Step 10 of 14Practice · What would you do?
What would you do?
A customer file has a zip column with values like "02139" and "07030". After pd.read_csv("customers.csv"), the column shows 2139 and 7030. What's the fix?
Step 11 of 14Note
Step 12 of 14Note
Step 13 of 14Practice · True or false
df.iloc[0:3] returns the rows at positions 0, 1 and 2, excluding position 3.
Step 14 of 14Practice · Choose one
Which expression returns a DataFrame (not a Series) containing only the price column?
Lesson complete!