Accessing elements of a Pandas Series

Accessing elements of a Pandas Series

A pandas Series is a one-dimensional labeled array capable of holding any data type. Here's how you can access elements of a pandas Series:

  • Using the Label/Index:

You can access the data in a Series just like you would with a dictionary:

import pandas as pd s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e']) print(s['a']) # 1 print(s['e']) # 5 
  • Using Position:

Just like with a list, you can use positional indices:

print(s[0]) # 1 print(s[4]) # 5 

You can also use negative indices for accessing elements from the end:

print(s[-1]) # 5 
  • Using .iloc[] for Positional Indexing:

The iloc attribute allows pure positional indexing:

print(s.iloc[0]) # 1 print(s.iloc[-1]) # 5 
  • Using .loc[] for Label-Based Indexing:

The loc attribute allows indexing and slicing that always references the explicit index:

print(s.loc['a']) # 1 print(s.loc['e']) # 5 
  • Slicing:

You can also slice a Series:

# Using explicit index for slicing print(s['a':'c']) 
a 1 b 2 c 3 dtype: int64 
# Using positional index for slicing print(s[0:2]) 
a 1 b 2 dtype: int64 
  • Boolean Indexing:

You can also use conditions to filter the values:

print(s[s > 3]) # elements greater than 3 
d 4 e 5 dtype: int64 
  • Accessing Multiple Elements:

To access multiple elements, you can pass a list of indices or labels:

print(s[[0, 2, 4]]) # by position print(s[['a', 'c', 'e']]) # by label 

Remember that if the Series has a non-integer index, using an integer to access an element will always use positional indexing. To ensure you're using the desired indexing (positional or label-based), it's a good practice to use iloc for positional and loc for label-based indexing.


More Tags

nl2br hapi.js memory-management find abstract password-protection noise android-sensors terminate external-links

More Programming Guides

Other Guides

More Programming Examples