Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting series element to int

Tags:

python

pandas

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?

like image 359
ubuntu_noob Avatar asked Oct 31 '25 15:10

ubuntu_noob


2 Answers

This should be more pythonic:

last_year = last_row_year.to_numpy()[0]
like image 150
Ann Zen Avatar answered Nov 02 '25 06:11

Ann Zen


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.

like image 34
cs95 Avatar answered Nov 02 '25 05:11

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!