Home > Blockchain >  Slice dataframe by range starting at the end of the frame
Slice dataframe by range starting at the end of the frame

Time:07-07

I have a dataframe like

df = pd.DataFrame({'one':[1,2,3,4,5],'two':['one','two','three','four','five']})

    c1    c2
0    1    one
1    2    two
2    3  three
3    4   four
4    5   five

which I would like to slice by a range starting at the last row, e.g index 1 to 3 but in a way that I could use it like I would use

.tail(-4:-1)

that would give me

    c1    c2
1    2    two
2    3  three
3    4   four

CodePudding user response:

That's what .loc and .iloc are for. Read more here

import pandas as pd

df = pd.DataFrame({'c1':[1,2,3,4,5],'c2':['one','two','three','four','five']})

print(df.iloc[-4:-1])

Output:

print(df.iloc[-4:-1])
   c1     c2
1   2    two
2   3  three
3   4   four
  • Related