How to Read First N Rows from DataFrame in Pandas?

Given a Pandas DataFrame, we have to read first N rows from it.
Submitted by Pranit Sharma, on June 20, 2022

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.

To read the first N rows of a DataFrame, we will use a parameter called nrows at the time of reading s CSV file by using pandas.read_csv() method.

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 code to Read First N Rows from DataFrame in Pandas

# Importing pandas package
import pandas as pd

# Reading a csv file
data = pd.read_csv('D:/Includehelp/mycsv.csv', nrows=2)

# Creating a Dataframe with first 2 rows
df = pd.DataFrame(data)

# Display Dataframe
print("Created DataFrame with first 2 rows of csv file:\n",df)


Example: Read First N Rows

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.