Pandas Series Tutorial: Create and Work with Series
A Pandas Series is a one-dimensional labelled data structure in Python. It stores a sequence of values together with an index that identifies each value. A Series is useful for representing a single variable, such as student marks, product prices, daily temperatures, monthly revenue or a list of customer ratings. In this tutorial, you will learn how to create a Pandas Series, work with index labels, access values, inspect its attributes, filter data and perform calculations using clear examples.
A Series is one of the two main data structures in pandas; the other is the DataFrame, which organises data into rows and columns. If you are new to the library, start with the introduction to Pandas, then return here to learn about Series in more detail.
- What is a Pandas Series?
- Create a Series from a list
- Understand Series index labels
- Create a Series from a dictionary
- Create a Series from a NumPy array
- Set a Series name and data type
- Access values by label and position
- Useful Series attributes and methods
- Filter Series values with conditions
- Perform calculations on a Series
- Handle missing values
- Series vs DataFrame
- Common mistakes
- Practice exercises
- Frequently asked questions
What Is a Pandas Series?
A Series is a one-dimensional array-like object with labelled values. It resembles a single column in a spreadsheet, but it is a Python object that supports data selection, calculations, missing-value handling and integration with other data-analysis tools.
A Series has two important parts:
- Values: the actual data, such as
78,91and84. - Index: labels associated with those values. If you do not provide labels, Pandas usually creates an integer index starting at zero.
For example, a Series of student marks could have three values and an index of 0, 1 and 2. You can also use meaningful labels such as student IDs, product names or dates.
import pandas as pd
marks = pd.Series([78, 91, 84])
print(marks)
Output
0 78 1 91 2 84 dtype: int64
The left-hand numbers are index labels, and the values on the right are the marks. The final line shows the data type Pandas has inferred for the values. Exact data types can depend on the values and the Pandas version.
How to Create a Pandas Series from a List
The simplest way to create a Series is to pass a Python list to pd.Series(). The values in the list become the Series data, and Pandas supplies a default index if you do not specify one.
import pandas as pd
prices = pd.Series([1200, 850, 430, 275])
print(prices)
Output
0 1200 1 850 2 430 3 275 dtype: int64
You can create a Series from strings, integers, decimal numbers, Boolean values and many other kinds of data. A Series normally has one inferred or explicitly specified dtype, although some dtypes can accommodate mixed or missing values.
product_names = pd.Series(["Laptop", "Phone", "Tablet"])
ratings = pd.Series([4.5, 4.2, 4.8])
available = pd.Series([True, False, True])
print(product_names)
print(ratings)
print(available)
Specify your own index
Pass the index argument when you want meaningful labels rather than the default zero-based index. The number of index labels must match the number of values.
marks = pd.Series(
[86, 73, 92],
index=["Amina", "Bilal", "Sara"]
)
print(marks)
Output
Amina 86 Bilal 73 Sara 92 dtype: int64
Pandas Series Index: Labels and Positions
The index associates a label with each value. Index labels can be integers, strings, dates or other supported label types. They are useful for identifying data and selecting specific entries.
Do not confuse an index label with a position. A position describes where an item appears in the current Series; a label is the identifier stored in its index. They may happen to be the same in a default Series, but they do not have to be.
marks = pd.Series(
[86, 73, 92],
index=["S101", "S102", "S103"]
)
print("Index:", marks.index)
print("Values:", marks.values)
print("First value by position:", marks.iloc[0])
print("Value with label S103:", marks.loc["S103"])
.loc when you want to select by index label and .iloc when you want to select by integer position. This distinction becomes particularly important after filtering or changing an index.Create a Pandas Series from a Dictionary
A Python dictionary stores key-value pairs. When you pass a dictionary to pd.Series(), its keys become the Series index and its values become the data. This is convenient when each value already has a meaningful label.
sales = {
"North": 12500,
"South": 9800,
"East": 11300,
"West": 8700
}
regional_sales = pd.Series(sales)
print(regional_sales)
You can then select a region by its label or calculate a total across the values:
print("North sales:", regional_sales.loc["North"])
print("Total sales:", regional_sales.sum())
If you pass an explicit index while creating a Series from a dictionary, Pandas aligns dictionary values to the requested labels. Labels that are not present in the dictionary receive missing values.
regional_subset = pd.Series(sales, index=["West", "North", "Central"])
print(regional_subset)
In this example, Central is not a key in the dictionary, so its value is missing. Check the result when supplying a custom index to avoid introducing unintended missing data.
Create a Series from a NumPy Array
You can also create a Series from a NumPy array. This is useful when numeric data has already been generated or processed with NumPy. NumPy is not required for the list and dictionary examples above.
import numpy as np
values = np.array([10, 20, 30, 40])
series_values = pd.Series(values, index=["a", "b", "c", "d"])
print(series_values)
Pandas can work with many array-like inputs, including lists and NumPy arrays. Choose the input type that best matches how your data is currently stored.
Set a Series Name and Data Type
The optional name argument gives a Series a descriptive name. This can help when displaying results or converting the Series into a DataFrame. The dtype argument can request a particular data type, provided the values can be represented by it.
marks = pd.Series(
[78, 91, 84],
index=["Amina", "Bilal", "Sara"],
name="ExamMark",
dtype="int64"
)
print(marks.name)
print(marks.dtype)
Use explicit data types when you have a reason to enforce them, such as preparing consistent numeric data. If the input contains invalid values for the requested dtype, Pandas may raise an error. Inspect the source data before converting it.
How to Access Pandas Series Values
There are several ways to retrieve values from a Series. Use the method that matches whether you know the index label, the integer position or a condition.
Access a value by label with loc
marks = pd.Series([86, 73, 92], index=["Amina", "Bilal", "Sara"])
print(marks.loc["Bilal"])
Access a value by position with iloc
print(marks.iloc[0]) # Value at the first position
print(marks.iloc[-1]) # Value at the last position
Select several values
Pass a list of labels to .loc or a list of positions to .iloc to return multiple entries.
print(marks.loc[["Amina", "Sara"]])
print(marks.iloc[[0, 2]])
For detailed examples of selecting rows and columns in a table, see how to select rows and columns in Pandas.
Useful Pandas Series Attributes and Methods
Attributes describe properties of a Series, while methods perform an operation. Attributes generally do not use parentheses; methods do.
| Attribute or method | Purpose | Example |
|---|---|---|
series.index | Returns the index labels. | marks.index |
series.values | Provides access to the underlying values as an array-like object. | marks.values |
series.dtype | Shows the Series data type. | marks.dtype |
series.name | Gets the Series name, if set. | marks.name |
series.shape | Returns a tuple describing its dimensions. | (3,) |
series.size | Returns the number of elements. | 3 |
series.ndim | Returns the number of dimensions; a Series has one. | 1 |
series.head() | Returns the first five entries by default. | marks.head(2) |
series.tail() | Returns the last five entries by default. | marks.tail(2) |
series.describe() | Summarises the distribution of values. | marks.describe() |
series.unique() | Returns distinct values. | marks.unique() |
series.nunique() | Counts distinct values (excluding missing values by default). | marks.nunique() |
print("Number of values:", marks.size)
print("Dimensions:", marks.ndim)
print("Data type:", marks.dtype)
print("Summary:")
print(marks.describe())
For a complete explanation of table dimensions and inspection methods, continue to the Pandas DataFrame tutorial.
Filter a Pandas Series with Conditions
Boolean filtering selects values that satisfy a condition. A comparison such as marks >= 80 produces a Boolean Series. Using that Boolean Series inside square brackets returns the entries where the condition is true.
marks = pd.Series(
[86, 73, 92, 68, 81],
index=["Amina", "Bilal", "Sara", "Omar", "Zara"]
)
high_marks = marks[marks >= 80]
print(high_marks)
Use parentheses around each condition when combining conditions with the bitwise operators & (AND), | (OR) and ~ (NOT). Do not use Python's and or or directly to combine whole Pandas Series conditions.
# Marks from 75 to 90, inclusive
selected = marks[(marks >= 75) & (marks <= 90)]
print(selected)
# Values below 80
print(marks[marks < 80])
Filtering a Series is useful for finding high marks, low sales values, unusual measurements or values that need further checking. For DataFrames, the same boolean-indexing idea can be used to filter rows based on column values.
Perform Calculations on a Pandas Series
Many calculations can be applied directly to an entire Series. Pandas performs these operations element by element where appropriate, which often makes the code shorter and easier to read than manually looping over each value.
daily_sales = pd.Series([1200, 850, 1430, 970, 1550])
print("Total:", daily_sales.sum())
print("Average:", daily_sales.mean())
print("Median:", daily_sales.median())
print("Minimum:", daily_sales.min())
print("Maximum:", daily_sales.max())
print("Count:", daily_sales.count())
To calculate a new value for every entry, use a vectorised expression:
prices = pd.Series([100, 250, 400])
prices_with_tax = prices * 1.15
print(prices_with_tax)
For many numeric operations, Pandas skips missing values by default. Check the documentation and the meaning of your data when the treatment of missing values could change the interpretation of a result.
Check and Handle Missing Values in a Series
Missing values can appear when data is incomplete or when an index label requested during Series creation is not present in the source dictionary. Pandas commonly represents missing numeric data with NaN, although other missing-value representations are available depending on the dtype.
scores = pd.Series([78, None, 91, 84])
print(scores)
print("Missing count:", scores.isna().sum())
print("Non-missing count:", scores.notna().sum())
Use isna() to identify missing values, dropna() to return a Series without missing entries, or fillna() to replace them. Choose a replacement based on what the values mean rather than automatically filling every missing entry with zero.
scores_without_missing = scores.dropna()
scores_filled = scores.fillna(scores.mean())
print(scores_without_missing)
print(scores_filled)
Read the dedicated guide to handling missing values in Pandas for more detailed examples.
Pandas Series vs DataFrame
A Series represents one labelled sequence of values. A DataFrame represents a two-dimensional table made up of rows and columns. Selecting a single column from a DataFrame using df["column"] usually returns a Series.
| Feature | Series | DataFrame |
|---|---|---|
| Dimensions | One-dimensional | Two-dimensional |
| Typical structure | One labelled sequence | Rows and one or more columns |
| Example | Student marks | Student names, marks and grades |
| Create with | pd.Series() | pd.DataFrame() |
| Dimension attribute | series.ndim == 1 | df.ndim == 2 |
marks = pd.Series([86, 73, 92], name="Marks")
marks_table = marks.to_frame()
print(type(marks))
print(type(marks_table))
print(marks_table)
Use a Series when one variable is the main focus. Use a DataFrame when you need to keep multiple related variables together. Learn more in the Pandas DataFrame guide or the DataFrame creation tutorial.
Common Pandas Series Mistakes
1. Confusing labels with positions
series.loc[label] selects by label, while series.iloc[position] selects by integer position. They may return different values when the index is not a default range of integers.
2. Supplying the wrong number of index labels
When creating a Series from a list with a custom index, the number of labels must match the number of values. Otherwise, Pandas raises a length mismatch error.
3. Using a missing dictionary key without checking the result
When an explicit index includes a label not found in a dictionary, the corresponding Series entry becomes missing. Inspect the result and check missing values when building a Series this way.
4. Treating a Series as a Python list
A Series supports many familiar operations, but it also has an index and Pandas-specific behaviour such as label alignment. When combining Series, Pandas commonly aligns values by their index labels rather than simply pairing values by position.
5. Combining conditions without parentheses
For combined filters, write expressions such as (series > 10) & (series < 50). Parentheses help ensure each comparison is evaluated as intended.
Pandas Series Exercises
Try these short exercises to check your understanding. Run your code in a Python environment with Pandas installed, then compare your approach with the hints.
- Create a Series from the list
[12, 18, 25, 31]. What is its default index? - Create a Series of three product prices and use product names as index labels.
- Given a Series of marks, select only values greater than or equal to 80.
- Use
sum()andmean()to calculate the total and average of a sales Series. - Create a Series from a dictionary and retrieve one value using
.loc. - Create a Series containing one missing value. Count missing entries and then return a version with missing values removed.
pd.Series(...) to create a Series, series[series >= 80] to filter values, series.isna().sum() to count missing values, and series.dropna() to return the non-missing entries.Frequently Asked Questions About Pandas Series
What is a Series in Pandas?
A Pandas Series is a one-dimensional labelled data structure. It contains values and an associated index, and is often used to represent one variable or a single column of data.
How do I create a Pandas Series?
Call pd.Series() and pass a list, dictionary, NumPy array or another supported input. You can optionally provide an index, name and data type.
What is the default index of a Pandas Series?
When no index is supplied, Pandas generally creates integer labels starting at zero: 0, 1, 2 and so on.
What is the difference between loc and iloc in a Series?
.loc selects entries by index label, while .iloc selects entries by integer position. Use the one that matches how you want to identify the entry.
How do I get the values of a Pandas Series?
You can inspect series.values for the underlying values or use series.to_list() to convert them into a regular Python list. Choose the form that best suits the next operation.
How do I find the number of items in a Series?
Use series.size for the total number of elements, including missing entries. Use series.count() to count non-missing values.
Can a Pandas Series contain missing values?
Yes. Use isna() to identify missing entries, dropna() to omit them or fillna() to replace them with a considered value.
What is the difference between a Series and a DataFrame?
A Series is one-dimensional; a DataFrame is two-dimensional and organises data into rows and columns. A DataFrame column is commonly represented as a Series.
What should I learn after Pandas Series?
Learn how to inspect a DataFrame, create tables, select and filter rows and columns, read CSV files, clean missing data and summarise datasets using groupby(). The complete Pandas tutorial provides a broader learning path.
Continue Learning Pandas
You have now learned how to create and work with a Pandas Series, use labels and positions, filter values, calculate summaries and check missing data. Continue with these related lessons:
