How do you get the first 3 rows in python?

Last update on August 19 2022 21:51:42 (UTC/GMT +8 hours)

Pandas: DataFrame Exercise-4 with Solution

Write a Pandas program to get the first 3 rows of a given DataFrame.

Sample DataFrame:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

Sample Solution :

Python Code :

import pandas as pd
import numpy as np

exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print("First three rows of the data frame:")
print(df.iloc[:3])

Sample Output:

First three rows of the data frame:                                    
   attempts       name qualify  score                                  
a         1  Anastasia     yes   12.5                                  
b         3       Dima      no    9.0                                  
c         2  Katherine     yes   16.5                                   

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to display a summary of the basic information about a specified DataFrame and its data.
Next: Write a Pandas program to select the 'name' and 'score' columns from the following DataFrame.

Python: Tips of the Day

Unzipping:

name = 'abcdef'
suffix = [1,2,3,4,5,6]
result = zip(name, suffix)
--> returns (a,1),(b,2),(c,3),(d,4),(e,5),(f,6)
unzipped = zip(*result)

To get the first N rows of a Pandas DataFrame, use the function pandas.DataFrame.head(). You can pass an optional integer that represents the first N rows. If you do not pass any number, it returns the first 5 rows. Meaning, the default N is 5.

Example 1: DataFrame.head(N)

In this example, we will get the first 3 rows of the DataFrame.

Python Program

import pandas as pd

#initialize a dataframe
df = pd.DataFrame(
	[[21, 72, 67],
	[23, 78, 62],
	[32, 74, 56],
	[73, 88, 67],
	[32, 74, 56],
	[43, 78, 69],
	[32, 74, 54],
	[52, 54, 76]],
	columns=['a', 'b', 'c'])

#get first 3 rows
df1 = df.head(3)

#print the dataframe
print(df1)

Run

Output

How do you get the first 3 rows in python?

Example 2: DataFrame.head()

In this example, we will not pass any number to the function head(). By default, head() function returns first 5 rows.

Python Program

import pandas as pd

#initialize a dataframe
df = pd.DataFrame(
	[[21, 72, 67],
	[23, 78, 62],
	[32, 74, 56],
	[73, 88, 67],
	[32, 74, 56],
	[43, 78, 69],
	[32, 74, 54],
	[52, 54, 76]],
	columns=['a', 'b', 'c'])

#get first default number of rows
df1 = df.head()

#print the dataframe
print(df1)

Run

Output

How do you get the first 3 rows in python?

Summary

In this Pandas Tutorial, we extracted the first N rows of Pandas DataFrame, using pandas.DataFrame.head() method, with the help of well detailed Python example programs.

  • Pandas iterrows() – Iterate over DataFrame Rows
  • How to iterate over Elements of Row in Pandas DataFrame?
  • How to Filter Pandas DataFrame Rows?
  • How to Add or Insert Row to Pandas DataFrame?
  • How to Count Rows in Pandas DataFrame?

How do I show the first 5 rows in Python?

DataFrame. head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start). By default n = 5, it return first 5 rows if value of n is not passed to the method.

How do you select the top 5 rows in Python?

In Python's Pandas module, the Dataframe class provides a head() function to fetch top rows from a Dataframe i.e. It returns the first n rows from a dataframe. If n is not provided then default value is 5.

How do you select a few rows in Python?

You can use one of the following methods to select rows in a pandas DataFrame based on column values:.
Method 1: Select Rows where Column is Equal to Specific Value df. loc[df['col1'] == value].
Method 2: Select Rows where Column Value is in List of Values. df. ... .
Method 3: Select Rows Based on Multiple Column Conditions df..

How do you extract the first row in Python?

You can get the first row with iloc[0] and the last row with iloc[-1] . If you want to get the value of the element, you can do with iloc[0]['column_name'] , iloc[-1]['column_name'] .