By the end of this lesson, you will be able to create, inspect, and manipulate a pandas Series, understanding how it differs from standard Python lists by providing labelled data structures.
What it is
A Series in pandas is a one-dimensional array-like object capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). Unlike a standard Python list, a Series has an associated index that labels each element. This allows for powerful alignment operations when combining data sets. Think of a Series as a single column in a spreadsheet or a database table where each row has a unique identifier.
Key related terms include Index (the labels), Values (the actual data), and Dtype (the data type of the values).
Why it matters
- Data Alignment: Operations between two Series automatically align data based on their index labels, not just their position.
- Labeled Access: You can access data using both integer positions and custom string labels.
- Vectorized Operations: Mathematical operations are applied to the entire array at once, which is significantly faster than looping through elements.
- Missing Data Handling: Series have built-in methods to detect and handle missing values (
NaN) gracefully.
Syntax or steps
The most common way to create a Series is by passing a list or dictionary to the pd.Series() constructor. If no index is provided, pandas creates a default integer index starting from 0. If a dictionary is passed, the keys become the index labels.
import pandas as pd
# From a list
s_list = pd.Series([10, 20, 30])
# From a dictionary
s_dict = pd.Series({'a': 1, 'b': 2})
Example
Let's look at a practical example involving temperature readings over three days.
import pandas as pd
# Create a Series with custom labels
temps = pd.Series(
[72, 68, 75],
index=['Mon', 'Tue', 'Wed'],
name='Temperature'
)
print(temps)
print("\nAccessing by label:", temps['Tue'])
print("Mean temperature:", temps.mean())
Explanation:
pd.Series(...): Initializes the Series object.[72, 68, 75]: The data values.index=['Mon', 'Tue', 'Wed']: Assigns specific string labels to each value instead of the default 0, 1, 2.name='Temperature': Gives the Series a descriptive title, useful for plotting or DataFrame conversion.temps['Tue']: Retrieves the value associated with the label 'Tue'.temps.mean(): Calculates the average of all numeric values in the Series.
Common mistakes
- Confusing Index vs. Position: Using
s[0]might return the first item if the index is default integers, but if the index is strings,s[0]may raise a KeyError. Uses.iloc[0]for positional access ands.loc['label']for label-based access to be explicit. - Mismatched Indices in Operations: Adding two Series with different indices results in
NaNfor non-overlapping labels. Always check indices before performing arithmetic. - Modifying Original Data: Some operations return a new Series, while others modify in place. Be cautious with chained assignments; use
.copy()if you need to isolate changes.
When to use it
Use a Series when working with a single column of data or a sequence of values that require labelling. Compare it with a NumPy array below:
| Feature | pandas Series | NumPy Array |
|---|---|---|
| Labels | Yes (Index) | No (Position only) |
| Heterogeneous Types | Yes (object dtype) | No (single dtype) |
| Best For | Data analysis, labeled datasets | Raw numerical computation |
Practice
Guided Exercise: Create a Series named sales containing the values [100, 200, 150] with the index ['Jan', 'Feb', 'Mar']. Print the total sales.
Challenge: Create a second Series returns with index ['Feb', 'Apr'] and values [10, 5]. Add sales and returns. What happens to 'Jan' and 'Apr'?
Hint: Check for NaN values in the result. Pandas aligns by index; missing matches become NaN.
Quick check
Q: How do you access the third element of a Series s by its position, regardless of its index label?
A: Use s.iloc[2].
Summary
A pandas Series is a fundamental building block for data analysis, offering labelled, one-dimensional arrays that support vectorized operations and automatic alignment. Mastering Series creation and indexing provides the foundation for working with larger DataFrames.