Pandas - item() has been deprecated

By xngo on February 19, 2020

I was using pandas.Series.item() function for a long time. Now, it is in the process of being removed. When running that function, I get the future deprecation warning:

FutureWarning: item has been deprecated and will be removed in a future version
print(df['year'].tail(1).item())

Solution

There are multiple ways to replace item(). It depends how you used that function. I mostly use it to get one value from a set. Here is a sample of different ways to replace it.

import pandas as pd
 
# Define pandas data frame.
df = pd.DataFrame()
df['year']  = [2005, 2006, 2008, 2013]
df['price'] = [  81,   43,   78,   65]
 
# Print last item, i.e. 2013.
#print( df['year'].tail(1).item() )
print( df['year'].tail(1).iat[0] )
print( df['year'].tail(1).iloc[0] )
print( df['year'].tail(1).values[0] )
print( df['year'].tail(1).values.item() )
print( next(iter(df['year'].tail(1)), 'no match') )

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.