Python Pandas - Display specific number of rows from a DataFrame

PythonServer Side ProgrammingProgramming

To display specific number of rows from a DataFrame, use the head() function. Set the parameter to be the number of row records to be fetched. For example, for 10 rows, mention −

dataFrame.head(10)

At first, let us import the required library with an alias −

import pandas as pd

Our CSV is on the Desktop as shown in the below path −

C:\\Users\\amit_\\Desktop\\CarRecords.csv

Let us read the CSV file and create Pandas DataFrame −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")

Return specific number of rows i.e. in this case, we are returning top 5 row records −

dataFrame.head(5)

Example

Following is the code

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# returns top 5 row records
print("DataFrame with specific number of rows...\n",dataFrame.head(5))

Output

This will produce the following output

DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi          95
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai         100
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100

DataFrame with specific number of rows ...
          Car      Place   UnitsSold
0        Audi  Bangalore          80
1     Porsche     Mumbai         110
2  RollsRoyce       Pune         100
3         BMW      Delhi          95
4    Mercedes  Hyderabad          80
raja
Published on 27-Sep-2021 13:19:53
Advertisements