How to Read First N Rows from DataFrame in Pandas?

Given a Pandas DataFrame, we have to read first N rows from it.
By Pranit Sharma Last updated : August 19, 2023

Rows in pandas are the different cell (column) values that are aligned horizontally and also provide uniformity. Each row can have the same or different value. Rows are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update and delete a column or row value.

Problem statement

Given a Pandas DataFrame, we have to read first N rows from it.

Read First N Rows from DataFrame in Pandas

To read the first N rows of a DataFrame, you can use DataFrame.head() method by specifying the number of rows to be read/returned. This function takes an argument n (number of rows) and returns the first n rows for the object based on position.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python Program to Read First N Rows from DataFrame in Pandas

import pandas as pd

data = {
    "students": ["Alex", "Alvin", "Bobs", "David", "Rechard", "Linda"],
    "age": [21, 19, 20, 21, 22, 23],
}

df = pd.DataFrame(data, columns=["students", "age"])

get_rows = df.head(4)

print(get_rows)

Output

  students  age
0     Alex   21
1    Alvin   19
2     Bobs   20
3    David   21

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.