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?
This should be more pythonic:
last_year = last_row_year.to_numpy()[0]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With