How to Find Median Staging Times and Spearman Correlation in Python

How to Find Median Staging Times and Spearman Correlation in Python EduTechBuddy.com © edutechbuddy.com
How to Find Median Staging Times and Spearman Correlation in Python © edutechbuddy.com
Learn how to calculate the median time for virtual staging tools and measure the relationship between generation time and structural drift using Spearman correlation in Python. This guide explains the process step by step with code and practical context.

Virtual staging platforms track how long it takes to generate a staged room and how much the result alters the original structure. Reviewing these records gives developers and researchers insight into tool performance and the link between processing time and output quality. This guide shows how to calculate the median staging time for each tool and use Spearman rank correlation to check how time and structural drift move together, using Python's standard library. The official Python documentation describes the statistics module as providing mathematical statistics functions for numeric data, including the median and correlation.

Understanding the Data Structure

Each record in the sample contains four elements: the tool identifier, the room identifier (as a string to keep leading zeros), the elapsed time in seconds, and the drift score. Drift shows how much the generated result changes the room's structure. Lower drift means better preservation. Some times are app estimates or ranges, and one record uses a fallback drift score because of alignment failure. The code works directly with the numeric values as recorded, without using the approximation flag. When working with educational datasets or digital learning platforms, document any estimated or fallback values as recommended in statistical best practices.

Calculating Median Staging Times by Tool

To summarize wait times, group the seconds by tool. The statistics.median function finds the middle value for each tool's list. If a tool has an even number of records, the median is the average of the two middle values. For example, in the sample, tool T02 has times of 18.6, 19.8, 18.6, and 22.0 seconds. The two middle values are 18.6 and 19.8, so the median is 19.20 seconds. Formatting to two decimal places makes the output easier to read. According to the Python documentation, the median is the "middle value" of numeric data, using the common "mean of middle two" method when the dataset contains an even number of values. This approach is especially useful in educational technology research and classroom analytics, where a small number of unusually long processing times could distort the arithmetic mean, making the median a more robust summary statistic for tool-level latency.

Ranking and Spearman Correlation

To check how time and drift relate, keep two lists in the same row order: one for seconds and one for drift scores. Spearman correlation measures how well the rankings of these two variables match. First, rank each column from smallest to largest. If values are tied, assign each the average of their positions. For example, two times of 18.6 seconds occupy positions 1 and 2, so each gets rank 1.5. The code uses a helper function to sort, group, and assign ranks while preserving the original pairing. This method follows the guidance in the Handbook of Biological Statistics, which states that Spearman rank correlation is used to test the association between two ranked variables, or one ranked variable and one measurement variable.

Once both columns are ranked, statistics.correlation calculates Pearson correlation on the ranks, which gives Spearman's rho. In the sample, the coefficient is close to zero, showing little association between time and drift. Across all 69 timed records in the full dataset, the coefficient is about -0.18, which suggests a weak negative relationship. These calculations use different sets of rows, so use the sample result to check the code and the full result to describe the complete data. The coefficient describes monotonic association and should not be presented as proof that processing time causes structural change. For educational data analysis, the median summarizes the center of a single variable, while Spearman correlation summarizes the monotonic relationship between two paired variables; they answer different analytical questions and should be labeled clearly, such as "record-level Spearman correlation" and "tool-level median staging time."

Python Implementation

The following code demonstrates the process using a sample of 12 records from tools T02, T04, and T06. The sample includes ties in both columns to test ranking behavior. Each tuple contains the tool, room, seconds, and drift score:

from collections import defaultdict
from itertools import groupby
from statistics import correlation, median

records = [
    ("T02", "01", 18.6, 11.0),
    ("T02", "02", 19.8, 24.1),
    ("T02", "03", 18.6, 21.7),
    ("T02", "04", 22.0, 56.5),
    ("T04", "01", 35, 27.1),
    ("T04", "02", 30, 26.6),
    ("T04", "03", 38.6, 33.5),
    ("T04", "10", 45, 26.6),
    ("T06", "06", 54, 22.5),
    ("T06", "08", 55, 27.4),
    ("T06", "09", 55, 10.2),
    ("T06", "10", 55, 21.2),
]

def average_ranks(values):
    ordered = sorted(enumerate(values), key=lambda item: item[1])
    ranks = [0.0] * len(ordered)
    first_rank = 1
    for _, group in groupby(ordered, key=lambda item: item[1]):
        tied = list(group)
        last_rank = first_rank + len(tied) - 1
        rank = (first_rank + last_rank) / 2
        for index, _ in tied:
            ranks[index] = rank
        first_rank = last_rank + 1
    return ranks

seconds_by_tool = defaultdict(list)
seconds = []
drift = []

for tool, room, elapsed, drift_score in records:
    seconds_by_tool[tool].append(elapsed)
    seconds.append(elapsed)
    drift.append(drift_score)

for tool, times in sorted(seconds_by_tool.items()):
    print(f"{tool} median: {median(times):.2f} s")
rho = correlation(average_ranks(seconds), average_ranks(drift))
print(f"Spearman rho: {rho:.6f}")

The output for this sample is:

T02 median: 19.20 s
T04 median: 36.80 s
T06 median: 55.00 s
Spearman rho: -0.031803

Working with Larger Datasets and Practical Tips

When analyzing a larger dataset, skip rows with blank seconds before building the paired lists. Keep the approximation flag available if you need to report how many times are app estimates or ranges. If either column is constant, Spearman correlation is undefined. You can still calculate each tool's median as long as it has at least one recorded time. The SciPy documentation notes that when ties are present, the exact approach is to compute Pearson's correlation on the average ranks, rather than using the shortcut formula. This ensures accurate results even when repeated times or drift scores occur in educational datasets or EdTech analytics.

If you want to see how this approach compares to other Python timing and data analysis techniques, check the timing guide for more context on measuring code performance.

Camila Ferreira Editor EduTechBuddy.com
Co-Founder

Camila Ferreira

Camila Ferreira is the Co-Founder of EduTechBuddy, where her editorial focus is programming education and practical software development skills. Her primary subjects include Python programming, Git version control, and the fundamental concepts beginners need to understand when working with code.