Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Slice dataframe by range starting at the end of the frame

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    c1    c2
1    2    two
2    3  three
3    4   four

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading