Pandas: How to Get Value from Series (3 Examples)


The following examples show how to get a value from a pandas Series in three different scenarios.

Method 1: Get Value from Pandas Series Using Index

The following code shows how to get the value in the third position of a pandas Series using the index value:

import pandas as pd

#define Series
my_series = pd.Series(['A', 'B', 'C', 'D', 'E'])

#get third value in Series
print(my_series[2])

C

By specifying the index value 2, we’re able to extract the value in the third position of the pandas Series.

Method 2: Get Value from Pandas Series Using String

The following code shows how to get the value that corresponds to a specific string in a pandas Series:

import pandas as pd

#define Series
my_series = pd.Series({'First':'A', 'Second':'B', 'Third':'C'})

#get value that corresponds to 'Second'
print(my_series['Second'])

B

Using this syntax, we’re able to get the value that corresponds to ‘Second’ in the pandas Series.

Method 3: Get Value from Pandas Series in DataFrame

The following code shows how to get the value in a pandas Series that is a column in a pandas DataFrame

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['Mavs', 'Spurs', 'Rockets', 'Heat', 'Nets'],
                   'points': [100, 114, 121, 108, 101]})

#view DataFrame
print(df)

      team  points
0     Mavs     100
1    Spurs     114
2  Rockets     121
3     Heat     108
4     Nets     101

#get 'Spurs' value from team column
df.loc[df.team=='Spurs','team'].values[0]

'Spurs'

By using the loc and values functions, we’re able to get the value ‘Spurs’ from the DataFrame.

Related: Pandas loc vs. iloc: What’s the Difference?

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Convert Pandas Series to NumPy Array
How to Get First Row of Pandas DataFrame
How to Get First Column of Pandas DataFrame

Leave a Reply

Your email address will not be published. Required fields are marked *