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
your_list = list(df['b'][-x-1:-x-n-1:-1])
I think in your case you can use
forward direction list(df['b'][x:(x+n)])
==>> [5,6,7]
or
backward direction list(df['b'][-(x)-1:-(x+n)-1:-1])
==> [7,6,5]
You can just do this:
n = -4
x = -1
lst = df.b.iloc[n:x].tolist()
print(lst)
Output:
[5, 6, 7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.