Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas head with offset

Tags:

python

pandas

What is the suggested way to get, for example, the first X rows after an offset of Y? What I'm currently doing is:

offset, limit = 2, 2
df=pd.DataFrame([{'a':1}, {'a': 2}, {'a':3}, {'a': 4}, {'a':5}])
df.head(offset+limit)[offset:]
#    a
# 2  3
# 3  4

Is there a better way to do this?

like image 230
David542 Avatar asked Mar 20 '26 22:03

David542


2 Answers

You can use df.iloc here.

df.iloc[offset: offset+limit]

   a
2  3
3  4
like image 106
Ch3steR Avatar answered Mar 22 '26 12:03

Ch3steR


There is closed GitHub issue which suggests using combination of head and tail

Something like this:

df.head(offset + limit).tail(limit)

This migh be bettet than accepted answer, cause due to docs iloc is "Deprecated since version 2.2.0"

like image 45
Alex Kosh Avatar answered Mar 22 '26 11:03

Alex Kosh