How to get items from a series object using the get() method?

PandasServer Side ProgrammingProgramming

The pandas series.get() method is used to get or retrieve the item from the series object for a given key. It will return the default value instead of raising KeyError if the specified key is not found in the series object.

The parameters for the get() method are key and default. Key is an object which is used to identify the item from the series. The default parameter has a default value which is None, we can change that value as required.

The get() method’s output is value and has the same type as items contained in the series object.

Example 1

Let’s take a series object and get the items from that object by specifying the key to the get() method.

# importing pandas package
import pandas as pd

# create pandas Series1
series = pd.Series([36, 79, 33, 58, 31, 97, 90, 19])

print("Initial series object:")
print(series)

# Apply get method with keyword
print("Output: ")
print(series.get(6))

Output

The output is given below −

Initial series object:
0    36
1    79
2    33
3    58
4    31
5    97
6    90
7    19
dtype: int64

Output:
90

The get() method successfully retrieved the element from the series object by using an integer key.

Example 2

Here, we will apply the get method using the string type key. The initial series object has string-type labels.

# importing pandas package
import pandas as pd

#creating pandas Series
series = pd.Series({'rose':'red', 'carrot':'orange', 'lemon':'yellow', 'grass':'green', 'sky':'blue'})

print(series)

print("Output: ")
# Apply the get() method with a key
print(series.get('lemon'))

Output

The output is given below −

rose         red
carrot    orange
lemon     yellow
grass      green
sky         blue
dtype: object

Output:
yellow

As we can notice in the above output block, the get() method has retrieved the item using the named indexed label.

Example 3

In the following example, we will get the items of a series object by using a list of keys.

# importing pandas package
import pandas as pd

#creating pandas Series
series = pd.Series({'rose':'red', 'carrot':'orange', 'lemon':'yellow', 'grass':'green', 'sky':'blue'})

print(series)

print("Output: ")
# Apply the get method with a list of keys
print(series.get(['lemon','grass']))

Output

The output is given below −

rose       red
carrot  orange
lemon   yellow
grass    green
sky       blue
dtype: object

Output:
lemon    yellow
grass     green
dtype: object

The get() method has successfully retrieved the list of items from the called series object. And the output is displayed in the form of a series object.

raja
Updated on 07-Mar-2022 11:05:17

Advertisements