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
Explain how series data structure in Python can be created using dictionary and explicit index values?
A Pandas Series is a one-dimensional labeled array that can be created from dictionaries. When you create a Series using a dictionary, the dictionary keys become the index labels, and the values become the data values.
Creating Series from Dictionary
When creating a Series from a dictionary, you can specify custom index values to control the order and selection of elements ?
import pandas as pd
my_data = {'ab': 11., 'mn': 15., 'gh': 28., 'kl': 45.}
my_index = ['ab', 'mn', 'gh', 'kl']
my_series = pd.Series(my_data, index=my_index)
print("Series created using dictionary with explicit index:")
print(my_series)
Series created using dictionary with explicit index: ab 11.0 mn 15.0 gh 28.0 kl 45.0 dtype: float64
How It Works
The dictionary provides key-value pairs where keys become index labels. When you specify an explicit index, Pandas matches the index values with dictionary keys to create the Series.
Index Values Greater Than Dictionary Keys
What happens when your index contains more values than the dictionary has keys? Let's examine this scenario ?
import pandas as pd
my_data = {'ab': 11., 'mn': 15., 'gh': 28., 'kl': 45.}
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("Series with extra index values:")
print(my_series)
Series with extra index values: ab 11.0 mn 15.0 gh 28.0 kl 45.0 wq NaN az NaN dtype: float64
Key Points
-
Missing keys: When index values don't exist in the dictionary, Pandas assigns
NaN(Not a Number) values - Order control: The explicit index parameter controls the order of elements in the Series
- Selective creation: You can specify only a subset of dictionary keys in the index to create a filtered Series
Practical Example
Here's a practical example showing how to select specific elements and control ordering ?
import pandas as pd
# Dictionary with student scores
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95}
# Create Series with specific order and subset
selected_students = ['Diana', 'Alice', 'Bob']
student_series = pd.Series(scores, index=selected_students)
print("Selected students with custom order:")
print(student_series)
Selected students with custom order: Diana 95 Alice 85 Bob 92 dtype: int64
Conclusion
Creating a Pandas Series from a dictionary with explicit index values gives you control over element selection and ordering. Missing keys result in NaN values, allowing flexible data structure creation.
