⊕
⊖
Contents
Pandas DataFrame – Get First N Rows – head()
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.
Examples
1. Get first three rows in DataFrame
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 Code CopyOutput
![Pandas DataFrame - Get First N Rows - head()](https://pythonexamples.org/wp-content/uploads/2019/06/pandas-dataframe-get-first-n-rows.webp)
2. Get first few rows of DataFrame
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 Code CopyOutput
![Pandas DataFrame - Get First N Rows - head()](https://pythonexamples.org/wp-content/uploads/2019/06/pandas-dataframe-get-first-n-rows-1.webp)
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.
Next Topic ⫸ Pandas DataFrame - Count rows
⫷ Previous Topic Pandas DataFrame - Add row