Baka Baka - 9 months ago 30
Python Question

Pandas dataframe, extract consecutive rows of a column to a list

I have, what seems to be a simple problem, but I cannot find an answer....

Assuming a pandas dataframe such as:

df = pd.DataFrame({"a": [1,2,3,4,5], "b": [4,5,6,7,8]})


In column
b
, I would like to extract a list containing the values of
n
consecutive rows starting
x
rows from the last row.

Assuming
n=3
and
x=1
, I would like to get:

list = [7,6,5] or list = [5, 6, 7]


I cannot figure out how to slice the relevant segment of dataframe to achieve this.

Any ideas?
Thank you !
Baka

Answer Source
your_list = list(df['b'][-x-1:-x-n-1:-1])