Five Number Summary in Python: pandas, NumPy & Matplotlib Guide

    By Oge Nwaozuzu6 min readUpdated: January 28, 2026

    Imagine you're analyzing a million customer transactions. Computing the five number summary by hand would take weeks. With pandas, it takes one line of code and 45 milliseconds. Here's how to harness Python's data science libraries for fast, flexible statistical summaries.

    Method 1: Using pandas describe()

    The fastest way to get the five number summary in Python is with pandas' describe() method:

    import pandas as pd
    
    # Your data
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45]
    
    # Create a Series and get summary
    series = pd.Series(data)
    summary = series.describe()
    
    print(summary)
    # Output:
    # count    10.000000
    # mean     27.000000
    # std      10.801234
    # min      12.000000
    # 25%      17.250000  <- Q1
    # 50%      26.500000  <- Median
    # 75%      36.250000  <- Q3
    # max      45.000000

    The describe() method returns the minimum (min), Q1 (25%), median (50%), Q3 (75%), and maximum (max)—exactly what you need.

    Extract Specific Values

    Access individual values like this: summary['25%'] for Q1, or summary['50%'] for median.

    Method 2: Using NumPy percentile()

    For more control, use NumPy's percentile() function:

    import numpy as np
    
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45]
    
    # Calculate all five values at once
    five_num = np.percentile(data, [0, 25, 50, 75, 100])
    
    minimum = five_num[0]  # 12.0
    q1 = five_num[1]       # 17.25
    median = five_num[2]   # 26.5
    q3 = five_num[3]       # 36.25
    maximum = five_num[4]  # 45.0
    
    print(f"Min: {minimum}, Q1: {q1}, Median: {median}, Q3: {q3}, Max: {maximum}")

    Method 3: Custom Function with All Components

    Here's a reusable function that calculates everything including IQR and outlier fences:

    import numpy as np
    
    def five_number_summary(data):
        """Calculate the five number summary with IQR and outlier fences."""
        data = np.array(data)
        
        minimum = np.min(data)
        q1 = np.percentile(data, 25)
        median = np.median(data)
        q3 = np.percentile(data, 75)
        maximum = np.max(data)
        
        iqr = q3 - q1
        lower_fence = q1 - 1.5 * iqr
        upper_fence = q3 + 1.5 * iqr
        
        # Find outliers
        outliers = data[(data < lower_fence) | (data > upper_fence)]
        
        return {
            'min': minimum,
            'q1': q1,
            'median': median,
            'q3': q3,
            'max': maximum,
            'iqr': iqr,
            'lower_fence': lower_fence,
            'upper_fence': upper_fence,
            'outliers': outliers.tolist()
        }
    
    # Example usage
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45, 95]  # 95 is an outlier
    result = five_number_summary(data)
    
    for key, value in result.items():
        print(f"{key}: {value}")

    Creating Box Plots with Matplotlib

    Visualize your five number summary with Matplotlib:

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45]
    
    # Create box plot
    fig, ax = plt.subplots(figsize=(8, 6))
    bp = ax.boxplot(data, vert=True, patch_artist=True)
    
    # Customize colors
    bp['boxes'][0].set_facecolor('#3b82f6')  # Blue fill
    bp['boxes'][0].set_alpha(0.7)
    
    # Add labels
    ax.set_ylabel('Values')
    ax.set_title('Five Number Summary Box Plot')
    
    # Add horizontal grid
    ax.yaxis.grid(True, linestyle='--', alpha=0.7)
    
    plt.tight_layout()
    plt.show()

    Creating Box Plots with Seaborn

    For more polished visualizations, use Seaborn:

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45]
    
    # Create a styled box plot
    plt.figure(figsize=(8, 6))
    sns.boxplot(y=data, color='#3b82f6', width=0.4)
    
    plt.ylabel('Values')
    plt.title('Five Number Summary')
    plt.tight_layout()
    plt.show()

    Compare Multiple Groups

    Seaborn excels at comparing box plots across categories. Use sns.boxplot(x='category', y='value', data=df) to compare groups side by side.

    Working with DataFrames

    When your data is in a DataFrame, you can calculate summaries for each column:

    import pandas as pd
    
    # Sample DataFrame
    df = pd.DataFrame({
        'sales': [120, 150, 180, 220, 250, 280, 300, 350, 400, 450],
        'costs': [80, 95, 110, 140, 160, 175, 190, 220, 250, 280]
    })
    
    # Get five number summary for all numeric columns
    print(df.describe())
    
    # Or for a specific column
    print(df['sales'].describe())
    
    # Create box plots for all columns
    df.boxplot(figsize=(10, 6))
    plt.title('Comparison of Sales and Costs')
    plt.show()

    Understanding Python's Quartile Method

    Python's default quartile calculation uses linear interpolation, matching Excel's QUARTILE.INC and our calculator's "Percentile" method. This means:

    • Results may differ slightly from TI-84 calculators
    • Small datasets may show fractional quartile values
    • This is the most common method in statistical software

    NumPy offers different interpolation methods via the method parameter (previously interpolation):

    import numpy as np
    
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    # Different methods
    print("Linear (default):", np.percentile(data, 25, method='linear'))
    print("Lower:", np.percentile(data, 25, method='lower'))
    print("Higher:", np.percentile(data, 25, method='higher'))
    print("Midpoint:", np.percentile(data, 25, method='midpoint'))

    Quick Reference: Copy-Paste Code

    Here's a minimal script you can copy and paste:

    import numpy as np
    
    # Replace with your data
    data = [12, 15, 18, 22, 25, 28, 30, 35, 40, 45]
    
    # Calculate five number summary
    min_val, q1, median, q3, max_val = np.percentile(data, [0, 25, 50, 75, 100])
    iqr = q3 - q1
    
    print(f"""
    Five Number Summary:
      Minimum: {min_val}
      Q1:      {q1}
      Median:  {median}
      Q3:      {q3}
      Maximum: {max_val}
      IQR:     {iqr}
    """)

    When to Use Python vs. the Calculator

    Use Python WhenUse the Calculator When
    Processing large datasetsYou need quick results
    Automating repeated analysesYou want instant visualization
    Integrating with other codeYou need multiple methods compared
    Creating custom visualizationsYou want step-by-step explanations

    Common Mistakes to Avoid

    These are the most frequent errors when calculating the five number summary in Python. Learn from these mistakes before you make them!

    Using df.describe() on non-numeric columns

    ✗ Wrong
    df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
    df.describe()  # Includes 'name' column - error or unexpected output

    TypeError or missing statistics for non-numeric columns

    Correct
    df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
    df.describe(include='number')  # Only numeric columns
    # Or: df['age'].describe()

    Clean five number summary for numeric data only

    💡 Why: describe() tries to analyze all columns by default. Use include='number' to filter to numeric columns, or select specific columns first.

    Wrong percentile method for matching other tools

    ✗ Wrong
    # Trying to match TI-84 calculator results
    np.percentile(data, 25)  # Uses linear interpolation by default

    Q1 = 17.25 (but TI-84 shows 17.0)

    Correct
    # To match TI-84 exclusive method
    np.percentile(data, 25, method='lower')
    # Or for more control:
    np.percentile(data, 25, method='midpoint')

    Q1 = 17.0 (matches TI-84)

    💡 Why: NumPy's default uses linear interpolation (like Excel QUARTILE.INC). To match TI-84, you need a different method parameter. Note: exact matching may still require manual calculation for odd-sized datasets.

    Forgetting to handle missing values (NaN)

    ✗ Wrong
    data = [1, 2, np.nan, 4, 5]
    np.percentile(data, 25)  # Returns nan!

    nan

    Correct
    data = [1, 2, np.nan, 4, 5]
    np.nanpercentile(data, 25)  # Ignores NaN values
    # Or: pd.Series(data).describe()  # pandas handles NaN

    1.75

    💡 Why: Regular percentile() propagates NaN. Use nanpercentile() to ignore missing values, or let pandas handle them automatically with dropna behavior.

    Calculating on unsorted data manually

    ✗ Wrong
    data = [5, 2, 8, 1, 9]
    # Manual median calculation without sorting
    median = data[len(data)//2]  # Gets 8, not the actual median!

    median = 8 (incorrect!)

    Correct
    data = [5, 2, 8, 1, 9]
    sorted_data = sorted(data)  # [1, 2, 5, 8, 9]
    median = sorted_data[len(data)//2]  # Gets 5
    # Or just use: np.median(data)  # Handles sorting automatically

    median = 5 (correct)

    💡 Why: NumPy and pandas functions sort internally, but if you calculate manually, you must sort first. This is the #1 mistake when learning.

    Performance Comparison: pandas vs NumPy

    Benchmarks on an M1 MacBook Pro (results may vary by hardware)

    Dataset Sizepandas describe()numpy percentile()Manual loop
    100 values0.8ms0.2ms15ms
    10,000 values2.1ms0.9msN/A
    1,000,000 values45ms12msN/A

    NumPy is 3-4× faster than pandas for pure percentile calculations. For exploratory analysis, pandas describe() provides more context. Manual loops are impractical for large datasets.

    Conclusion

    Python offers powerful, flexible tools for calculating the five number summary. Whether you use pandas for quick summaries, NumPy for precise control, or Matplotlib for visualization, you have everything needed for professional data analysis.

    For quick calculations without writing code, try our Five Number Summary Calculator—it's instant and shows step-by-step working.

    Verify Your Calculations

    Use the free five number summary calculator to check your work.

    Open Calculator

    Written by Oge Nwaozuzu

    Statistics educator and data analyst. Creator of 5numbersummarycalculator.app.