How to Retrieve a Value from a Series in Python?

Estimated read time 2 min read

To retrieve a value from a pandas Series in Python, you can use indexing or the .loc[] and .iloc[] accessors. Here’s an example:

import pandas as pd

# Create a sample Series
data = {'A': 1, 'B': 2, 'C': 3}
series = pd.Series(data)

# Retrieve a value using indexing
value = series['B']
print(value)  # Output: 2

# Retrieve a value using .loc[]
value = series.loc['C']
print(value)  # Output: 3

# Retrieve a value using .iloc[]
value = series.iloc[0]
print(value)  # Output: 1

In this example, we create a sample Series series using a dictionary data. The keys of the dictionary become the index labels, and the values become the corresponding values in the Series.

To retrieve a value from the Series:

  • Using indexing: You can directly access a value by specifying the index label as the index inside square brackets, such as series['B']. This retrieves the value corresponding to the index label 'B'.
  • Using .loc[]: The .loc[] accessor allows you to retrieve a value by specifying the index label explicitly, such as series.loc['C']. This retrieves the value corresponding to the index label 'C'.
  • Using .iloc[]: The .iloc[] accessor allows you to retrieve a value by specifying the integer position of the value, starting from 0. For example, series.iloc[0] retrieves the value at the first position in the Series.

You can use the appropriate method based on whether you want to retrieve the value based on the index label or the position in the Series.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply