w3resource

Compute Statistical properties of NumPy array with SciPy


1. Random Array Statistical Properties

Write a NumPy program that creates a NumPy array of random numbers and uses SciPy to compute the statistical properties (mean, median, variance) of the array.

Sample Solution:

Python Code:

# Import necessary libraries
import numpy as np
from scipy import stats

# Create a NumPy array of random numbers
data = np.random.rand(100)

# Compute the mean of the array using SciPy
mean = stats.tmean(data)

# Compute the median of the array using SciPy
median = np.median(data)

# Compute the variance of the array using SciPy
variance = stats.tvar(data)

# Print the statistical properties
print("Mean:", mean)
print("Median:", median)
print("Variance:", variance)

Output:

Mean: 0.4879592058849749
Median: 0.49297261150369925
Variance: 0.09259159781167492

Explanation:

  • Import the necessary libraries:
    • Import NumPy and SciPy's "stats" module.
  • Create a NumPy array of random numbers:
    • Generate an array of 100 random numbers between 0 and 1.
  • Compute the mean:
    • Use SciPy's tmean function to calculate the mean of the array.
  • Compute the median:
    • Use NumPy's median function to calculate the median of the array.
  • Compute the variance:
    • Use SciPy's tvar function to calculate the variance of the array.
  • Finally display the mean, median, and variance.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to create a random array and compute its skewness and kurtosis using SciPy's stats module.
  • Write a Numpy program to generate a random array and compare the results of np.mean with SciPy's describe function.
  • Write a Numpy program to produce a random array and compute its confidence interval for the mean using SciPy.
  • Write a Numpy program to create a random array and perform a normality test (e.g., Shapiro-Wilk) using SciPy's stats module.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: NumPy Integration Exercises Home.
Next: Perform 2D discrete Fourier Transform using SciPy's fftpack.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.