Pandas Series get()

The get() method in Pandas is used to retrieve a single item from a Series using its index.

Example

import pandas as pd

# create a Series
series = pd.Series([10, 20, 30], index=['a', 'b', 'c'])

# use the get() method to retrieve the value at index 'b' value = series.get('b')
print(value) # Output: 20

get() Syntax

The syntax of the get() method in Pandas is:

Series.get(key, default=None)

get() Arguments

The get() method takes following arguments:

  • key - the index label of the item to retrieve
  • default (optional) - the default value to return if the key is not found

get() Return Value

The get() method returns the value at the specified index if it exists in the Series. Otherwise, returns the specified default value.


Example1: Retrieve a Single Item From a Series

import pandas as pd

# create a Series with strings and custom index labels
data = pd.Series(['apple', 'banana', 'cherry'], index=['x', 'y', 'z'])

# use get() to retrieve the value at index 'y' value = data.get('y')
print(value) # Output: banana

In the above example, we have created the data Series with strings apple, banana, and cherry, each associated with the index labels x, y, and z, respectively.

The get() method is used to retrieve the value at the index label y.


Example 2: Retrieve With Default Value

import pandas as pd

# create a Pandas Series with strings and custom index labels
data = pd.Series(['apple', 'banana', 'cherry'], index=['x', 'y', 'z'])

# use get() to retrieve the value at index 'a', with a default value
value = data.get('a', default='Not Found')

print(value)

# Output: Not Found

Here, we created the Series named data with elements apple, banana, and cherry, indexed by x, y, and z.

We used the get() method to try to retrieve the value at the index a, which does not exist in this Series.

Since a is not a valid index in our Series, the get() method returns the default value we specified, Not Found.