Pandas DataFrame Select Rows

November 27, 2020

Init data

import pandas as pd

items = [
    ["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
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.