Learning to Use Numpy Library in PythonLearning to Use Numpy Library in Python
Spread the love

Loading

NumPy – A Replacement for MatLab

NumPy is often used along with packages like SciPy (Scientific Python) and Matplotlib (plotting library). This combination is widely used as a replacement for Matlab, a popular platform for technical computing. However, Python alternative to Matlab is now seen as a more modern and complete programming language.

Installation

In the terminal, type:

>>>pip3 install numpy

Code Example | Creating 2D Numpy Array

np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79],

 [65.4, 59.2, 63.6, 88.4, 68.7]])

 print(np_2d.shape)

Code Example | Calculating BMI

import numpy as np

np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])

np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])

bmi = np_weight / np_height ** 2

print(” BMI : “, bmi)

Basic Statistical Analysis

import numpy as np

np_city = np.array([[ 1.64, 71.78],

[ 1.37, 63.35],

[ 1.6 , 55.09],

[ 2.04, 74.85],

[ 2.04, 68.72],

[ 2.01, 73.57]])

print(np_city)

print(type(np_city))

print(“Mean Height : “,np.mean(np_city[:,0]))

print(“Median Height : “,np.median(np_city[:,0]))

np.corrcoef(np_city[:,0], np_city[:,1])

np.std(np_city[:,0])

fam = [1.73, 1.68, 1.71, 1.89]

tallest = max(fam)

print(“Tallest : “, tallest)

Data Generation and Statistics

Random.normal is used to draw random samples from a normal (Gaussian) distribution. For example, we can generate 1000 samples with mean mu and standard deviation sigma as follows:

mu, sigma = 0, 0.1 # mean and standard deviation

s = np.random.normal(mu, sigma, 1000)

height = np.round(np.random.normal(1.75,0.20,5000),2)

weight = np.round(np.random.normal(60.32,15,5000),2)

np_city = np.column_stack((height,weight))

print(np_city)

By Hassan Amin

Dr. Syed Hassan Amin has done Ph.D. in Computer Science from Imperial College London, United Kingdom and MS in Computer System Engineering from GIKI, Pakistan. During PhD, he has worked on Image Processing, Computer Vision, and Machine Learning. He has done research and development in many areas including Urdu and local language Optical Character Recognition, Retail Analysis, Affiliate Marketing, Fraud Prediction, 3D reconstruction of face images from 2D images, and Retinal Image analysis in addition to other areas.