Sub topic 2
DataFrames and Series in a nutshell
This chapter assumes you know basic Python (variables, lists, dictionaries) and have pandas installed. It covers the two objects you will use in every later chapter: the Series and the DataFrame.
The two core objects
A Series is a one-dimensional labeled array. It holds values of a single dtype (data type) and has an index that labels each value.
A DataFrame is a two-dimensional table. Each column is a Series, and all the columns share one row index. When you read the Titanic CSV in the next chapter, you get one DataFrame. Each column, such as Age or Sex, is a Series.
Building a small DataFrame
A dictionary of lists is the quickest way to build one by hand. Each key becomes a column name.
import pandas as pd
passengers = pd.DataFrame({
"Name": ["Allen", "Braund", "Cumings", "Dean"],
"Pclass": [1, 3, 1, 3],
"Sex": ["female", "male", "female", "male"],
"Age": [29.0, 22.0, 38.0, None],
"Survived": [1, 0, 1, 0],
})
print(passengers.shape)
print(passengers.dtypes)
print(passengers.index)shape is a tuple of (rows, columns), here (4, 5). dtypes shows one type per column. Age is float64 because None became NaN (not a number), pandas' marker for a missing value. Integer columns cannot hold NaN in the default dtype, so a column with a gap is converted to float. index shows the row labels. Unless you set otherwise, they are the integers 0 to n-1.
Pulling out a Series
Square brackets with one column name return a Series. Brackets with a list of names return a DataFrame.
age = passengers["Age"]
print(type(age))
print(age.mean())
subset = passengers[["Name", "Age"]]
print(type(subset))age.mean() prints about 29.67. The NaN is skipped, so the mean covers three values, not four. Most pandas reductions skip missing values by default. That is convenient, but it can hide a problem, which later chapters return to.
Operations apply to whole columns
Arithmetic and comparisons on a Series work element by element, with no loop. This is called vectorization.
print(passengers["Age"] + 1)
print(passengers["Age"] >= 18)
print(passengers["Sex"].str.upper())The comparison returns a Series of booleans, with the same index as the original. You will use these boolean Series as filters in the chapter on selecting rows. A comparison against NaN gives False, so a missing age is not counted as an adult. That is a quiet source of errors.
Why the index matters
When you combine two Series, pandas aligns them by index label, not by position. Two Series with the same labels line up row by row. Rows with different labels produce NaN. For a single table loaded from a CSV this rarely causes trouble, but it explains some surprising results after you filter rows. A filtered DataFrame keeps its original labels, so row 0 may be gone while row 5 remains.
Quick reference
| Object | Dimensions | Typical source | Key attributes |
|---|---|---|---|
| Series | 1 | One column of a DataFrame | `dtype`, `index`, `name` |
| DataFrame | 2 | `pd.read_csv`, a dictionary of lists | `shape`, `dtypes`, `columns`, `index` |
Exercise
Using the passengers DataFrame above, what type does passengers["Pclass"] return, and what type does passengers[["Pclass"]] return?
Show answer
passengers["Pclass"] returns a Series, because you passed a single name. passengers[["Pclass"]] returns a DataFrame with one column, because you passed a list. You can check with type(...).
Exercise
Why is the Age column's dtype float64 and not int64, even though the ages are whole numbers?
Show answer
One value is missing. The default integer dtype cannot store NaN, so pandas stores the column as floats, where NaN is allowed.