atomxkai
atomxkai

Reputation: 49

How to select first N rows and last row in Python Pandas?

Problem: Select first N rows and last row in Python Pandas.

only gets 1 row which is index 9 and last row.

df.iloc[[(9),-1]]

I thought I could get using head and last row but not working.

df.iloc[[head(9),-1]]

Target output: 0 1 2 3 up to 9 last row

Upvotes: 1

Views: 4416

Answers (3)

MD. SHIFULLAH
MD. SHIFULLAH

Reputation: 1769

Here is I providing code with sample output:

Code:

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
    'Age': [25, 30, 22, 35, 28],
    'Salary': [50000, 60000, 45000, 70000, 55000]
}

df = pd.DataFrame(data)

first_3_rows = df.head(3)
print("First 3 rows:")
print(first_3_rows)
print("\n")


last_2_row = df.tail(2) 
print("Last 2 row:")
print(last_2_row)

Output:

First 3 rows:
Name  Age  Salary
0    Alice   25   50000
1      Bob   30   60000
2  Charlie   22   45000


Last 2 row:
Name  Age  Salary
3  David   35   70000
4  Emily   28   55000

Upvotes: 0

Ned Hulton
Ned Hulton

Reputation: 678

head = df.head(9)
tail = df.tail(1)
df = head.append(tail)

I think you just want this. Please clarify if this is wrong.

Output:

    first_column  second_column
0              0              0
1              1              1
2              2              2
3              3              3
4              4              4
5              5              5
6              6              6
7              7              7
8              8              8
12            12             12

This is assuming I understand correctly, you want 9 rows and also the last.

Upvotes: 3

user7864386
user7864386

Reputation:

You could use numpy.concatenate:

import numpy as np
out = df.iloc[np.r_[0:9, -1]]

or just list concatenation:

out = df.iloc[list(range(9))+[-1]]

Test:

For a DataFrame:

df = pd.DataFrame({'a':range(20), 'b':range(100,120)})

the output:

     a    b
0    0  100
1    1  101
2    2  102
3    3  103
4    4  104
5    5  105
6    6  106
7    7  107
8    8  108
19  19  119

Upvotes: 2

Related Questions