Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to retrieve multiple elements from a series when the index is customized Python?
When working with Pandas Series that have customized index values, you can retrieve multiple elements by passing a list of index values. This allows flexible data access using meaningful labels instead of numeric positions.
Basic Syntax
To access multiple elements from a series with custom index ?
series_name[['index1', 'index2', 'index3']]
Note the double square brackets [[]] − the inner brackets create a list of index values, while the outer brackets perform the indexing operation.
Example
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("The series contains following elements:")
print(my_series)
print("\nAccessing multiple elements using customized index:")
print(my_series[['mn', 'az', 'wq', 'ab']])
The series contains following elements: ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 Accessing multiple elements using customized index: mn 56 az 45 wq 123 ab 34 dtype: int64
Key Points
Use double square brackets
[[]]when accessing multiple elementsThe order of elements in the result matches the order specified in the index list
Index values must exist in the original series, otherwise a
KeyErroris raisedThe returned result is also a Pandas Series with the same data type
Alternative Methods
You can also use the loc accessor for the same operation ?
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("Using loc accessor:")
print(my_series.loc[['mn', 'az', 'wq']])
Using loc accessor: mn 56 az 45 wq 123 dtype: int64
Conclusion
Use double square brackets [[]] to retrieve multiple elements from a series with custom index. The loc accessor provides an alternative approach for label-based selection.
