VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/05/mathematical-operations-in-python-with-numpy/

⇱ Mathematical Operations in Python with Numpy | Numpy Math Operations


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Mathematical Operations in Python with Numpy

Prateek Majumder Last Updated : 25 Oct, 2024
5 min read

This article was published as a part of the Data Science Blogathon

Introduction

Numpy which stands for Numeric Python is a Python library used for working with arrays. It also has functions for working in the domain of linear algebra, Fourier transform, and matrices.

NumPy was created in 2005 by Travis Oliphant as an open-source project and one can use it freely.

πŸ‘ mathematical operations in numpy

Why Numpy?

Numpy is a Python library that is written in Python, but the parts that require fast computation are written in C or C++. For this reason, working with Numpy array is much faster than working with Python lists.

Numpy being an open-source project has thousands of contributors working to keep NumPy fast, friendly, and bug-free. Numpy is hugely popular these days due to its use in various fields and tasks.

πŸ‘ Uses of numpy

Uses of Numpy :

Numpy has numerous uses. Normal arithmetic and statistical operations are simple to implement Numpy. Various trigonometric calculations can also be done. Other uses are broadcasting, linear algebra, matrix operations, stacking, copying and manipulating arrays.

NumPy contains a multi-dimensional array and matrix data structures, making large scale calculations simple and easy.

Numpy Arrays explained (https://predictivehacks.com/tips-about-numpy-arrays/)

Numpy has random number generators which can be used for various tasks like noise generation for signals for just random probability generations and other mathematical tasks.

Numpy Basics :

Let us start with the basics of Numpy.

Python Code:

import numpy as np
#numpy array 
a= np.array([34,67,8,5,33,90,23]) 
print(a)

Output: [34 67 8 5 33 90 23]

#type
type(a)

Output: numpy.ndarray

print(a[2])

Output : 8

b=np.array([[77, 38, 9], [10, 11, 12]])
print(b)

Output:

[[77 38 9] [10 11 12]]

Now, we look at some interesting functions in NumPy.

Ones: Creates a NumPy array according to the parameters given, with all elements being 1.

np.ones(5)

array([1., 1., 1., 1., 1.])

np.ones([6,7])

Output:

array([[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.]])

Zeros: Creates a NumPy array according to the parameters given, with all elements being 0.

np.zeros(7)

Output :  array([0., 0., 0., 0., 0., 0., 0.])

These functions are simple, they can be used to create sample arrays which are often needed for various computational purposes.

eye: Let us now look at the eye function. This function returns a 2-D array with ones on the diagonal and zeros elsewhere.

np.eye(5)

Output:

array([[1., 0., 0., 0., 0.],

[0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]])

Similarly, the diag() function creates a 2D array with the elements passed as diagonal elements and other elements being zero.

y=np.array([6,78,3,56,89])
np.diag(y)

Output:

array([[ 6, 0, 0, 0, 0],

[ 0, 78, 0, 0, 0], [ 0, 0, 3, 0, 0], [ 0, 0, 0, 56, 0], [ 0, 0, 0, 0, 89]])

Let us try some more interesting functions. These are self-explanatory.

np.array([1, 2, 3,7] * 3)

Output : array([1, 2, 3, 7, 1, 2, 3, 7, 1, 2, 3, 7])

np.repeat([1, 4, 2, 3], 5)

Output : array([1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3])

p = np.ones([2, 3], int)
print(p)

Output :

[[1 1 1] [1 1 1]]

With vstack(), we can vertically append data, and with hstack(), we can horizontally stack data. Let us try out some examples.

np.vstack([p, 2*p])

Output :

array([[1, 1, 1],

[1, 1, 1], [2, 2, 2], [2, 2, 2]])
np.vstack([3*p, 2*p, 6.5*p,4.6*p])

Output :

array([[3. , 3. , 3. ],

[3. , 3. , 3. ], [2. , 2. , 2. ], [2. , 2. , 2. ], [6.5, 6.5, 6.5], [6.5, 6.5, 6.5], [4.6, 4.6, 4.6], [4.6, 4.6, 4.6]])
np.hstack([2*p,5.5*p,9*p])

Output:

array([[2. , 2. , 2. , 5.5, 5.5, 5.5, 9. , 9. , 9. ],

[2. , 2. , 2. , 5.5, 5.5, 5.5, 9. , 9. , 9. ]])

Numpy Mathematical Computation :

Let us get onto working with NumPy in various mathematical computations.

import numpy as np
a=np.array([4,6,8])
b=np.array([8,9,7])

c=a+b

print(c)

Output: [12 15 15]

Now, we go for an element by element multiplication.

a=np.array([4,6,8])
b=np.array([8,9,7])

c=a*b

print(c)

Output : [32 54 56]

Element by element division.

a=np.array([4,6,8])
b=np.array([8,9,7])

c=a/b

print(c)

Output: [0.5         0.66666667 1.14285714]

We calculate the dot product now.

c=np.array([6,7,5,8])
d=np.array([4,3,7,8])

ans=c.dot(d) #dot product

print(ans)

Output : 144

Let us now, look at how to create multi-dimensional numpy arrays.

z=np.array([[5,7,5,4,5],[6,2,3,4,6]])

print(z)

Output:

[[5 7 5 4 5] [6 2 3 4 6]]

Getting the transpose.

print(z.T)

Output :

[[5 6] [7 2] [5 3] [4 4] [5 6]]

Let us create a list by giving a few parameters. The first and second parameter will be for determining the range and the third will be for the interval.

h=np.arange(4,90,5)
print(h)

Output: [ 4 9 14 19 24 29 34 39 44 49 54 59 64 69 74 79 84 89]

Now, let us look at some standard functions.

πŸ‘ output

Let us carry some computations over multi-dimensional arrays.

test = np.random.randint(0,10,(4,3))
print(test)

Output:

[[5 0 2]
[3 6 0]
[5 7 7]
[0 5 9]]

Here 0 and 10 indicate the range, and 4,3 is the shape of the matrix/2D array.

test2 = np.random.randint(90,120,(8,3))
test2

Output:

array([[106, 103, 104],
[ 96, 93, 106],
[110, 108, 115],
[117, 106, 114],
[ 91, 102, 103],
[ 98, 104, 92],
[112, 99, 105],
[115, 111, 118]])

for row in test2:
 print(row)

Output:

[106 103 104] [ 96 93 106] [110 108 115] [117 106 114] [ 91 102 103] [ 98 104 92] [112 99 105] [115 111 118]
test3 = test2**2
test3

Output:

array([[11236, 10609, 10816],
[ 9216, 8649, 11236],
[12100, 11664, 13225],
[13689, 11236, 12996],
[ 8281, 10404, 10609],
[ 9604, 10816, 8464],
[12544, 9801, 11025],
[13225, 12321, 13924]], dtype=int32)

for i, j in zip(test2, test3):
 print(i,'+',j,'=',i+j)

Output:

[106 103 104] + [11236 10609 10816] = [11342 10712 10920]
[ 96 93 106] + [ 9216 8649 11236] = [ 9312 8742 11342]
[110 108 115] + [12100 11664 13225] = [12210 11772 13340]
[117 106 114] + [13689 11236 12996] = [13806 11342 13110]
[ 91 102 103] + [ 8281 10404 10609] = [ 8372 10506 10712]
[ 98 104 92] + [ 9604 10816 8464] = [ 9702 10920 8556]
[112 99 105] + [12544 9801 11025] = [12656 9900 11130]
[115 111 118] + [13225 12321 13924] = [13340 12432 14042]

Conclusion

Thus, we can see that NumPy can be used for various types of mathematical calculations and the important thing is that the computation time is much less than python lists. This helps while working in real-life cases with millions of data points.

Numpy array is also very convenient to use with a lot of data manipulation tricks and methods.

Do connect with me on Linkedin

Thank You.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

Prateek is a dynamic professional with a strong foundation in Artificial Intelligence and Data Science, currently pursuing his PGP at Jio Institute. He holds a Bachelor's degree in Electrical Engineering and has hands-on experience as a System Engineer at TCS Digital, where he excelled in API management and data integration. Prateek also has a background in product marketing and analytics from his time with start-ups like AppleX and Milkie Way, Inc., where he was involved in growth campaigns and technical blog management. Recognized for his structured thinking and problem-solving abilities, he has received accolades like the Dr. Sudarshan Chakraborty Award for Best Student Performance. Fluent in multiple languages and passionate about technology, Prateek continues to expand his expertise in the rapidly evolving AI and tech landscape.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner