Let us first create a dataframe and then we will try to get first 3 rows of this dataframe using several methods.
Code: Creating a Dataframe.
Getting first 3 Rows of the above Dataframe :
Method 1: Using head(n) method.
This method returns top n rows of the dataframe where n is an integer value and it specifies the number of rows to be displayed. The default value of n is 5 therefore, head function without arguments gives the first five rows of the dataframe as an output. So to get first three rows of the dataframe, we can assign the value of n as ‘3’.
Below is the code for getting first three rows of the dataframe using head() method:
Method 2: Using iloc[ ].
This can be used to slice a dataframe by using the starting index and ending index of the sliced dataframe that we want.
Syntax: dataframe.iloc[statrt_index, end_index+1]
So if we want first three rows, i.e. from index 0 to index 2, we can use the following code:
Method 3: Using index of the rows.
iloc[ ] method can also be used by directly stating the indices of the rows we want in the iloc method. Say to get row with indices m and n iloc[ ] can be used as:
Syntax: Dataframe.iloc [ [m,n] ]
Following is the code to get first three rows of the dataframe using this method:
- Get all rows in a Pandas DataFrame containing given substring
- How to get rows/index names in Pandas dataframe
- Get the number of rows and number of columns in Pandas Dataframe
- Get minimum values in rows or columns with their index position in Pandas-Dataframe
- Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
- Shuffle a given Pandas DataFrame rows
- Python | Delete rows/columns from DataFrame using Pandas.drop()
- How to randomly select rows from Pandas DataFrame
- Different ways to iterate over rows in Pandas Dataframe
- Selecting rows in pandas DataFrame based on conditions
- How to iterate over rows in Pandas Dataframe
- Sorting rows in pandas DataFrame
- Dealing with Rows and Columns in Pandas DataFrame
- Iterating over rows and columns in Pandas DataFrame
- Ranking Rows of Pandas DataFrame
- Create a list from rows in Pandas dataframe
- Create a list from rows in Pandas DataFrame | Set 2
- Drop rows from the dataframe based on certain condition applied on a column
- How to Drop Rows with NaN Values in Pandas DataFrame?
- Drop rows from Pandas dataframe with missing values or NaN in columns
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.