List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Use head and tail Functions in Pandas

Pandas head and tail function output

Condition for Using head and tail Functions in Pandas

  • Description:
    In Pandas, the head() and tail() functions are used to quickly preview the top and bottom rows of a DataFrame, respectively. These functions are particularly helpful when you are working with large datasets and want to get a quick snapshot of the first or last few entries.

    head(): Returns the first n rows of a DataFrame (default is 5).
    tail(): Returns the last n rows of a DataFrame (default is 5).
Step-by-Step Process
  • Import Pandas:
    Ensure you have imported the Pandas library.
  • Create or Load a DataFrame:
    Prepare a dataset using a dictionary, list, or load data from a CSV or other file formats.
  • Use head():
    Call the head() function to view the top n rows of the DataFrame.
  • Use tail():
    Call the tail() function to view the bottom n rows of the DataFrame.
  • Specify the Number of Rows:
    Pass an integer argument to retrieve a specific number of rows.
Sample Source Code
  • # Code for head and tail functions

    import pandas as pd

    data = {
    "Name": ["Alice", "Bob", "Charlie", "David", "Eva", "Frank", "Grace"],
    "Age": [25, 30, 28, 35, 40, 32, 29],
    "Salary": [50000, 60000, 55000, 70000, 65000, 72000, 52000]
    }
    df = pd.DataFrame(data)

    # Using head() to view the first 3 rows
    print("Top 3 rows of the DataFrame:")
    print(df.head(3))

    # Using tail() to view the last 2 rows
    print("\nLast 2 rows of the DataFrame:")
    print(df.tail(2))

    # Displays the first 5 rows by default
    print("\nDisplays first 5 rows")
    print(df.head())

    # Displays the last 5 rows by default
    print("\nDisplays last 5 rows")
    print(df.tail())
Screenshots
  • Pandas head and tail output