Sub topic 1
Columns are Series: the building block
Every operation in this tutorial creates, changes, or replaces a column. A column is not a plain list of values. It is a pandas Series, and a Series carries an index, a dtype, and a name. These three properties explain how column arithmetic lines up rows, how types are chosen, and why some assignments give surprising results. This chapter builds that model first. Later chapters rely on it.
Prerequisites
This chapter assumes you can:
- Write basic Python, including functions and lambdas.
- Create a pandas DataFrame from a dictionary and select a column by name.
- Read simple NumPy-style array arithmetic. NumPy knowledge is helpful but not required.
The examples use pandas 2.x. Install it with pip install pandas if needed.
A column is a Series
Selecting one column with single brackets returns a Series.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
price = df["price"]
print(type(price))
print(price.dtype)
print(price.name)
print(price.index)The output is:
<class 'pandas.core.series.Series'>
float64
price
RangeIndex(start=0, stop=3, step=1)A Series has three parts that matter for column work:
- Values: a one-dimensional array of data, usually stored as a NumPy array.
- dtype: a single data type for the whole column, such as
float64,int64,object,string, ordatetime64[ns]. - Index: labels for each value. A DataFrame shares one index across all its columns.
A DataFrame behaves like a dictionary of Series that share an index. That is why you can pull out one column, compute with it, and put the result back under a new key.
flowchart TD
A[DataFrame] --> B["df['price'] returns a Series"]
A --> C["df['qty'] returns a Series"]
A --> D["df['item'] returns a Series"]
B --> E[values: 1.5, 12.0, 30.0]
B --> F[dtype: float64]
B --> G[index: 0, 1, 2]
B --> H[name: price]Because the diagram needs the exact fence format, here it is in the required form.
Series versus one-column DataFrame
Single brackets and double brackets return different types.
print(type(df["price"])) # Series
print(type(df[["price"]])) # DataFrame
print(df["price"].shape) # (3,)
print(df[["price"]].shape) # (3, 1)Use df["price"] when you want to compute with a column. Use df[["price"]] when you want a table that happens to have one column. A common error is passing a one-column DataFrame where a Series is expected. For example, assigning df[["price"]] * 2 to a single new column can raise an error or produce a column of unexpected shape. If your result looks two-dimensional, check the brackets.
Selecting columns safely
You can reach a column in two ways.
df["price"] # bracket access: always works for existing columns
df.price # attribute access: works only for some namesAttribute access fails or misleads in several cases:
- The name contains spaces or punctuation, such as
"unit price". - The name collides with a DataFrame method or attribute, such as
count,size,index, orT.df.sizereturns the number of cells, not your column. - The column does not exist yet.
df.total = ...sets a plain Python attribute and does not create a column. pandas warns about this.
Use brackets for anything that writes, and prefer them for reads too.
Operating on Series
Arithmetic and comparisons on a Series apply to every element and return a new Series with the same index. No loop is needed. This is called vectorization, and the next chapters build on it.
total = df["price"] * df["qty"]
print(total)
print(df["price"] > 10)The output is:
0 15.0
1 36.0
2 60.0
dtype: float64
0 False
1 True
2 True
Name: price, dtype: boolTwo details are worth noticing. First, the result of multiplying price and qty has no name, because the two inputs have different names. Second, the comparison keeps the name price, because only one Series was involved. Names rarely matter until you place a Series in a new column, because the column key you assign to becomes the name.
The dtype of the result follows NumPy rules. A float64 times an int64 is float64. An integer column divided by an integer column with / is float64.
Index alignment
When two Series are combined, pandas matches values by index label, not by position. This is the most important idea in the chapter, and it also applies when you assign a Series into a DataFrame.
s = pd.Series([100, 200, 300], index=[2, 1, 0])
df["bonus"] = s
print(df[["item", "bonus"]])The output is:
item bonus
0 pen 300
1 book 200
2 lamp 100The Series was listed in the order 2, 1, 0. pandas matched label 0 to row 0, so pen gets 300, not 100. A plain list, by contrast, is placed by position.
df["bonus"] = [100, 200, 300]
print(df[["item", "bonus"]])Now pen gets 100. The same numbers produce different columns depending on whether they arrive as a list or as a Series with a shuffled index.
Labels with no match become NaN
If a label is missing from the Series, the corresponding rows get NaN, which stands for "not a number" and marks a missing value.
partial = pd.Series([5, 6], index=[0, 1])
df["partial"] = partial
print(df["partial"])The output is:
0 5.0
1 6.0
2 NaN
Name: partial, dtype: float64The dtype changed from int64 to float64. Integer NumPy arrays cannot hold NaN, so pandas upgrades the column to floats. This silent upgrade is a common source of surprise, and a later chapter covers missing values in detail.
Length mismatches
Lists and arrays are not aligned by label, so their length must match the number of rows.
try:
df["bad"] = [1, 2]
except ValueError as err:
print(err)The message is Length of values (2) does not match length of index (3). A Series of any length is accepted, because alignment decides what happens, and unmatched rows become NaN.
Alignment in arithmetic
Alignment also applies between Series in an expression. After you filter or sort a DataFrame, its index labels no longer run in order. Arithmetic still pairs the right rows.
expensive = df[df["price"] > 5]
ratio = expensive["price"] / df["price"]
print(ratio)The result has all three labels. Row 0 was filtered out of expensive, so its ratio is NaN. Rows 1 and 2 are 1.0. Alignment is correct here, but if you expected only two rows, you now have a gap to handle.
Duplicate labels
Alignment assumes the index labels are unique. If the index has duplicate labels, assigning a Series can fail with cannot reindex on an axis with duplicate labels. If you hit that error after concatenating DataFrames, call reset_index(drop=True) first, or build the new column from a NumPy array with .to_numpy(). A NumPy array has no index, so it is placed by position.
Reading a column's dtype before changing it
Every later technique depends on the dtype, so check it first.
print(df.dtypes)Typical findings:
objectfor text, or for a column mixing numbers and strings.int64orfloat64for numeric columns.datetime64[ns]for parsed dates.boolfor yes/no columns.
An object column that looks numeric is a warning sign. Arithmetic on it either fails or concatenates strings. For example, "1" * 3 is "111". Convert such columns before computing, a topic for a later chapter.
Summary of the model
| Property | What it controls | Typical problem |
|---|---|---|
| Values | The data in each row | Wrong length when assigning a list |
| dtype | Which operations work and how results are typed | Numbers stored as `object`, int upgraded to float |
| Index | How rows are matched across Series | Shuffled or partial index produces `NaN` or misplaced values |
| Name | The label a Series carries | Rarely matters until you assign it as a column |
Exercise
Given df = pd.DataFrame({"a": [1, 2, 3]}), what does df["b"] = pd.Series([10, 20, 30], index=[1, 2, 3]) produce in column b, and what is its dtype?
Show answer
Labels are matched, not positions. Label 0 has no match, so row 0 gets NaN. Label 1 gets 10 and label 2 gets 20. Label 3 does not exist in df and is dropped. Column b is [NaN, 10.0, 20.0] with dtype float64, because the NaN forces a float column.
Exercise
You run df.total = df["price"] * df["qty"] and no total column appears in df.columns. Why, and what is the fix?
Show answer
Attribute assignment on a DataFrame sets a plain Python attribute and does not create a column. Use bracket assignment: df["total"] = df["price"] * df["qty"].