Sub topic 2
DataFrames and Series in a Nutshell
This chapter assumes you know basic Python (variables, lists, dictionaries, functions) and have pandas installed. Every later chapter uses two objects, the Series and the DataFrame. This chapter builds a working model of both. You will need it to read the Titanic data correctly and to understand the errors pandas raises.
What a Series is
A Series is a one-dimensional labeled array. It has three parts:
- values: a block of data, all of one dtype (data type).
- index: one label per value.
- name: an optional label for the whole Series.
import pandas as pd
ages = pd.Series([22.0, 38.0, 26.0, None], name="Age")
print(ages)
print(ages.dtype)
print(ages.index)The None becomes NaN (not a number), the marker pandas uses for a missing numeric value. Because NaN is a float, the whole Series has dtype float64. The index is a RangeIndex with labels 0 to 3, which pandas creates when you don't supply one.
A Series is not a Python list. A list can mix types freely. A Series stores one dtype and applies operations to all values at once, which is called vectorization.
print(ages + 1)
print(ages.mean())
print(ages > 25)ages + 1adds 1 to every value, and the missing value stays missing.ages.mean()skipsNaNby default, so it averages the three known ages and prints about 28.67.ages > 25returns a Series of booleans. The comparison withNaNgivesFalse, not "unknown". This matters later, because a filter on age silently drops rows where age is missing.
What a DataFrame is
A DataFrame is a two-dimensional table. You can think of it as a dictionary of Series that share one index. Each column is a Series, and each column can have its own dtype.
passengers = pd.DataFrame(
{
"Name": [
"Braund, Mr. Owen",
"Cumings, Mrs. John",
"Heikkinen, Miss. Laina",
"Allen, Mr. William",
],
"Sex": ["male", "female", "female", "male"],
"Age": [22.0, 38.0, 26.0, None],
"Pclass": [3, 1, 3, 3],
"Survived": [0, 1, 1, 0],
}
)
print(passengers.shape)
print(passengers.dtypes)
print(passengers.columns)
print(passengers.index)This small table imitates the Titanic columns, so you can experiment before you load the real file in the next chapter. The shape attribute is a tuple of (rows, columns), here (4, 5). The dtypes attribute lists one dtype per column. Age is float64, Pclass and Survived are int64, and the text columns are object. In recent pandas versions the text columns may show as str.
Getting a Series or a DataFrame from a DataFrame
The most common beginner error is confusing a single column with a one-column table. The brackets decide which one you get.
print(type(passengers["Age"]))
print(type(passengers[["Age"]]))
print(type(passengers[["Name", "Age"]]))| Expression | Result | Shape |
|---|---|---|
| `passengers["Age"]` | Series | 1-D, 4 values |
| `passengers[["Age"]]` | DataFrame | 4 rows, 1 column |
| `passengers[["Name", "Age"]]` | DataFrame | 4 rows, 2 columns |
The inner brackets are a Python list of column names. A string gives one column as a Series. A list of strings gives a smaller DataFrame. Some methods behave differently on each, so check the type when a result looks odd.
Columns are also reachable as attributes, as in passengers.Age. Avoid this habit. It fails for names with spaces, and it collides with existing methods. For example, df.count is the method, not a column called count.
The index: labels, not just row numbers
The index is what separates pandas from a plain array. It labels rows, and pandas uses those labels when it combines data. This is called alignment. Operations between two Series match values by label, not by position.
a = pd.Series([1, 2, 3], index=["a", "b", "c"])
b = pd.Series([10, 20, 30], index=["b", "c", "d"])
print(a + b)The result has four labels. Labels b and c appear in both Series, so they give 12 and 23. Labels a and d appear in only one Series, so both give NaN. The dtype becomes float64 because of the NaN values.
Alignment explains a quiet source of bugs. When you assign a Series to a DataFrame column, pandas matches by index label, not by row position. If you filter or sort a Series and then assign it back, the values still land on the correct rows. If the labels don't match, you get NaN instead of an error.
You can change which column acts as the index with set_index.
by_name = passengers.set_index("Name")
print(by_name.loc["Braund, Mr. Owen", "Age"])
print(by_name.iloc[0, 1])locselects by label.ilocselects by integer position.
In the Titanic file, the PassengerId column is a natural index candidate. For a first exploration, the default RangeIndex works well. A custom index is not required.
After you filter rows, the index keeps its original labels. A table of the survivors might have labels 1, 2, 5. It does not renumber to 0, 1, 2. Use reset_index(drop=True) when you want fresh labels.
survivors = passengers[passengers["Survived"] == 1]
print(survivors.index)
print(survivors.reset_index(drop=True).index)dtypes and why they matter
Each column has one dtype, and the dtype decides which operations make sense.
int64andfloat64hold numbers. Statistics likemeanandcorrwork on them.object(orstr) holds text. Arithmetic on it fails or gives odd results.boolholdsTrueandFalse.categoryholds a fixed set of labels. You will meet it when you bin ages.
An integer column cannot hold NaN in the default int64 dtype. If a column of integers contains a missing value, pandas converts the whole column to float64. This is why Age is a float even though ages look like whole numbers. Sometimes a column you expect to be numeric loads as object, because a stray string such as "?" is mixed in. Checking dtypes early catches this.
You can convert a dtype explicitly.
passengers["Pclass"] = passengers["Pclass"].astype("category")
print(passengers.dtypes)Do this only when you have a reason. Here, a category tells readers that Pclass is a label (first, second, third class), not a quantity you should average.
Adding and changing columns
Assigning to a new column name creates a column. Because operations are vectorized, you rarely need a loop.
passengers["IsChild"] = passengers["Age"] < 13
passengers["AgeInMonths"] = passengers["Age"] * 12
print(passengers[["Name", "Age", "IsChild", "AgeInMonths"]])Allen's age is missing, so IsChild is False for him. That is an artifact of how comparisons treat NaN. It does not mean he is an adult. Whenever you derive a column from one that has missing values, decide what the missing rows should become.
Copies and chained indexing
Filtering with a boolean mask returns a new DataFrame. Writing into that result can trigger a SettingWithCopyWarning, or in recent pandas it may do nothing to the original. The safe pattern is to make the copy explicit.
adults = passengers[passengers["Age"] >= 18].copy()
adults["Adult"] = True
print(adults)Calling .copy() tells pandas you want an independent table. Without it, you might be modifying a temporary object. Do the same for any subset you plan to add columns to.
Summary
- A Series is one labeled column of one dtype. A DataFrame is a set of Series sharing one index.
df["col"]returns a Series, anddf[["col"]]returns a DataFrame.- The index labels rows. Operations and assignments align on labels, and filtering keeps the original labels.
NaNforces integer columns to float and makes comparisons returnFalse.- Use
.copy()on subsets you will modify, andlocfor assignment.
Exercise
You run sub = passengers[passengers["Pclass"] == 1] and then sub["Age"] + passengers["Age"]. The result has four entries, and only the row for "Cumings, Mrs. John" has a number. Why? Then name two ways passengers["Age"] and passengers[["Age"]] differ.
Show answer
Series arithmetic aligns on index labels. sub keeps only the label 1, so that is the only label present in both Series, and the other three labels give NaN. The two expressions differ in type (a Series versus a one-column DataFrame) and in shape (1-D versus 2-D). The outer brackets select a column by name, and the inner brackets are a list of names.
Exercise
A column Count holds the integers 3, 5, and a missing value. What dtype does pandas give it, and why?
Show answer
It gives float64. The default int64 dtype cannot store NaN, so pandas converts the whole column to floating point to hold the missing value.