Compute Statistical properties of NumPy array with SciPy
NumPy: Integration with SciPy Exercise-1 with Solution
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/compute-statistical-properties-of-numpy-array-with-scipy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics