[Python] need help on z test , t test, and regreesion

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    import numpy as np from statsmodels.stats.weightstats import ztest import matplotlib.pyplot as plt import seaborn as sns from scipy import stats

    def perform_one_sample_z_test(sample_data, population_mean_hypothesized, population_std, alpha=0.05): """ Performs a one-sample Z-test.

    Args:
    sample_data (array-like): The sample observations.
    population_mean_hypothesized (float): The hypothesized population mean (mu_0).
    population_std (float): The known population standard deviation (sigma).
    alpha (float): The significance level (default is 0.05).

    Returns:
    tuple: A tuple containing:
    - z_statistic (float): The calculated Z-statistic.
    - p_value (float): The p-value from the Z-test.
    - interpretation (str): A string interpreting the results.
    """
    sample_mean = np.mean(sample_data)
    n = len(sample_data)

    print(f"--- One-Sample Z-Test ---")
    print(f"Sample Size (n): {n}")
    print(f"Sample Mean: {sample_mean:.4f}")
    print(f"Hypothesized Population Mean (μ₀): {population_mean_hypothesized}")
    print(f"Known Population Standard Deviation (σ): {population_std}")
    print(f"Significance Level (α): {alpha}")

    # Perform the Z-test
    # The 'value' parameter in ztest is the hypothesized population mean
    # 'ddof=0' for population standard deviation (n-0 in denominator for std calc if used from sample, but here we provide known pop_std)
    # The default 'alternative' is 'two-sided'
    z_statistic, p_value = ztest(x1=sample_data, value=population_mean_hypothesized, ddof=0, x2=None)

    interpretation = ""
    if p_value < alpha:
    interpretation = (f"Since the p-value ({p_value:.4f}) is less than alpha ({alpha}), "
    "we reject the null hypothesis.\n"
    "Conclusion: There is statistically significant evidence that the sample mean "
    f"({sample_mean:.4f}) is significantly different from the hypothesized population mean "
    f"({population_mean_hypothesized}).")
    else:
    interpretation = (f"Since the p-value ({p_value:.4f}) is greater than or equal to alpha ({alpha}), "
    "we fail to reject the null hypothesis.\n"
    "Conclusion: There is no statistically significant evidence to suggest that the sample mean "
    f"({sample_mean:.4f}) is significantly different from the hypothesized population mean "
    f"({population_mean_hypothesized}).")

    print(f"\nZ-statistic: {z_statistic:.4f}")
    print(f"P-value: {p_value:.4f}")
    print(interpretation)

    return z_statistic, p_value, interpretation

    Continue reading...

Compartilhe esta Página