Access last item of list

Question:

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.

Answers:

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

Answered By: fire_demesne

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
Answered By: ScottC
[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]
Answered By: JayPeerachai

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]
Answered By: U12-Forward
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.