In Pandas, the head()
method is used to return the first few rows of a DataFrame. This method is often used to quickly inspect the data in a DataFrame, or to get a sense of the data before performing more detailed analyses.
To use the head()
method, we first need to import the Pandas library and create a DataFrame
object.
Here is an example of how to use the head()
method to return the first few rows of a DataFrame:
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7, 8], 'B': [9, 10, 11, 12, 13, 14, 15, 16]})
# Use head() to return the first few rows
print(df.head())
A B
0 1 9
1 2 10
2 3 11
3 4 12
4 5 13
This will return the first five rows of the DataFrame
, with the column names as the row labels and the values in each row as the column values.
If the DataFrame
has fewer than five rows, head()
will return all the rows in the DataFrame
.
To customize the result, we can use the optional n
parameter of the head()
method.
This parameter specifies the number of rows to return, and if it is not specified, the default value is five.
Here is an example of how to use the n
parameter to specify the number of rows to return:
# Use head() to return the first two rows
print(df.head(2))
A B
0 1 9
1 2 10
In addition to returning the first few rows of a DataFrame
, the head()
method can also be used to return the first few rows of a Series
.
To do this, we can use the head()
method on the Series
object, in the same way as we would use it on a DataFrame
.
Here is an example:
# Create a Series
s = pd.Series([10, 20, 30, 40, 50])
# Use head() to return the first few rows
print(s.head())
0 10
1 20
2 30
3 40
4 50
dtype: int64
This will return the first five elements of the Series
, with the index labels as the row labels and the values as the column values.
If the Series
has fewer than five elements, head()
will return all the elements in the Series
.
Related tutorials curated for you
How to use where() in Pandas
How to calculate the standard deviation in Pandas DataFrame
How to write a Pandas DataFrame to SQL
How to use nunique() in Pandas
How to apply a function to multiple columns in Pandas
How to give multiple conditions in loc() in Pandas
What is categorical data in Pandas?
How to select multiple columns in Pandas
Pandas read SQL
How to convert a series to a NumPy array in Pandas
What is Pandas Cumsum()?
How to fix: AttributeError module 'pandas' has no attribute 'dataframe'