David542
David542

Reputation: 110432

Pandas head with offset

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?

Upvotes: 3

Views: 2103

Answers (2)

Alex Kosh
Alex Kosh

Reputation: 2554

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"

Upvotes: 0

Ch3steR
Ch3steR

Reputation: 20679

You can use df.iloc here.

df.iloc[offset: offset+limit]

   a
2  3
3  4

Upvotes: 8

Related Questions