'Converting series element to int

I have a pandas series-

3959    2019
Name: DATE, dtype: int64

which has only one element.

I wanted to convert that element to integer. I did-

for i in last_row_year.to_numpy():
    last_year=i

to get last_year as 2019 (int type)

Is there a more pythonic way to do this?



Solution 1:[1]

Singleton series can be converted to a scalar via .item():

s = pd.Series([1]) 
s 

0    1
dtype: int64

s.item()
# 1

Note that this only works on series of length 1. For a more generic solution that always grabs the first element of any series regardless of length, .iloc[0] or .to_numpy()[0] is preferred.

Solution 2:[2]

If you have a series with only one element, int(element) will suffice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Emerson Harkin