Thursday, 14 September 2023

Pandas: A Guide to Traversing Series

In this post, I am going to explain different ways to traverse the Pandas Series.

Approach 1: Using for loop and series index attribute.

for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

Approach 2: Using enumerate method.

for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

Approach 3: Using series items method.

for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

traverse_series.py

import pandas as pd

primes_list = [2, 3, 5, 7]
index_labels = ['A', 'B', 'C', 'D']
series = pd.Series(primes_list, index=index_labels)

# Using for loop and series index attribute.
print('Using for loop and series index attribute.')
for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

# Using enumerate method
print('\nUsing for loop and series index attribute.')
for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

# Using series items method
print('\nUsing series items method')
for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

Output

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7

Using for loop and series index attribute.
Index: 0, Label: A, Value: 2
Index: 1, Label: B, Value: 3
Index: 2, Label: C, Value: 5
Index: 3, Label: D, Value: 7

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7


Previous                                                 Next                                                 Home

No comments:

Post a Comment