A Series is a one-dimensional labelled array. It holds values of one type, and every value has a label called the index. Each column of a DataFrame is a Series.
Prerequisites
Creating a Series
import pandas as pd
s = pd.Series([88, 95, 72])
print(s)
Explanation: The left column is the default index (0, 1, 2); the right column holds the values.
0 88 1 95 2 72 dtype: int64
Custom Index
marks = pd.Series([88, 95, 72], index=['Asha', 'Ravi', 'Neha'])
print(marks['Ravi'])
print(marks.index.tolist(), marks.values)
95 ['Asha', 'Ravi', 'Neha'] [88 95 72]
From a Dictionary
population = pd.Series({'Delhi': 32.9, 'Mumbai': 21.3, 'Ludhiana': 1.9})
print(population)
Explanation: Dictionary keys become the index. These values are example figures in millions.
Delhi 32.9 Mumbai 21.3 Ludhiana 1.9 dtype: float64
Vectorised Operations and Filtering
print(marks + 5)
print(marks[marks > 80])
print(marks.mean(), marks.max(), marks.idxmax())
Asha 93 Ravi 100 Neha 77 dtype: int64 Asha 88 Ravi 95 dtype: int64 85.0 95 Ravi
Index Alignment
a = pd.Series([1, 2, 3], index=['x', 'y', 'z'])
b = pd.Series([10, 20], index=['y', 'z'])
print(a + b)
Explanation: pandas matches values by index label, not position. Labels missing from one Series give NaN (missing).
x NaN y 12.0 z 23.0 dtype: float64
loc and iloc
print(marks.loc['Asha']) # by label
print(marks.iloc[0]) # by position
88 88
Common Errors
| Problem | Cause and fix |
|---|---|
KeyError |
The label is not in the index. Check s.index. |
| Unexpected NaN after maths | Indexes did not match; see Index Alignment. |
Practice Exercises
- Create a Series of 7 daily temperatures with day names as the index and find the hottest day.
- Add 10% to every value of a price Series.
Interview Questions
Q: What happens when you add two Series with different indexes?
They are aligned by label; unmatched labels give NaN.
Q: loc vs iloc?
loc selects by label, iloc by integer position.
Summary
A Series is a labelled 1D array. Create it from lists or dicts, use loc/iloc to select, and remember operations align on the index.
Next: Pandas DataFrame
Machine Learning Tutorials, Courses and Certifications