Home > database >  Access last item of list
Access last item of list

Time:12-26

This is really embarrassing but I can't figure out why the list[-1] method doesn't return the last item from the list.

Here is the series:

[df1['Close'] / highest(df1['Close'],20) > 1]

Output is as follows:

[2415    False
 2416    False
 2417    False
 2418    False
 2419    False
         ...  
 5614    False
 5615    False
 5616    False
 5617    False
 5618    False
 Name: Close, Length: 3204, dtype: bool]

Now I try to access the last element through:

[df1['Close'] / highest(df1['Close'],20) > 1][-1]

It still throws the same output as above. I must be doing something wrong.

I can convert this to a series & it works.

(df1['Close'] / highest(df1['Close'],20) > 1).iloc[-1:]

But that's not how I want to use it.

CodePudding user response:

Your code is returning a pandas.Series within a list. So when you access [-1], you are getting the pandas series inside of the list. You can access the last value of the pandas.Series, by calling .values[-1].

Like this:

  • access the pandas Series in the list by using [0]
  • access last value of the series with .values[-1]

Code:

[df1['Close'] / highest(df1['Close'],20) > 1][0].values[-1]

Output:

False

CodePudding user response:

Using square brackets ([ ]) would construct a list. Use parentheses instead:

(df1['Close'] / highest(df1['Close'],20) > 1)[-1]

Or use functions:

df1['Close'].div(highest(df1['Close'], 20)).gt(1)[-1]

Or the best is with iloc:

df1['Close'].div(highest(df1['Close'], 20)).gt(1).iloc[-1]

CodePudding user response:

[df1['Close'] / highest(df1['Close'],20) > 1]

This code only return everything as one element in list. So, [-1] will return a whole thing.

Try .iloc without putting the series inside a list:

(df1['Close'] / highest(df1['Close'],20) > 1).iloc[-1]

CodePudding user response:

you can also use some_list[len(some_list)-1] which gives the last element

  • Related