Pandas DataFrame Select Rows

Nov 27, 2020

Init data

import pandas as pditems = [    ["A", 1],    ["B", 2],    ["C", 3],    ["D", 4],    ["E", 5]]data = pd.DataFrame(items, columns=['alphabet', 'number'])print(data)
  alphabet  number
0        A       1
1        B       2
2        C       3
3        D       4
4        E       5

Get first row

data.head(1)
  alphabet  number
0        A       1

Get first n row

data.head(3)
  alphabet  number
0        A       1
1        B       2
2        C       3

Get last row

data.tail(1)
  alphabet  number
4        E       5

Get last n row

data.tail(3)
  alphabet  number
2        C       3
3        D       4
4        E       5

Get first row

data.iloc[0:1]
  alphabet  number
0        A       1

Get second row

data.iloc[1:2]
  alphabet  number
1        B       2

Get second to forth row

data.iloc[1:4]
  alphabet  number
1        B       2
2        C       3
3        D       4

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.