How to Do Simple Math on NumPy Arrays
Mohamed Riyaz Khan
Data Scientist in Tech | Leveraging Data for Insights | Seeking New Challenges | Driving Impact | Python | Machine Learning | Data Analysis | SQL | TensorFlow | NLP
Hey, young explorer! Today, we'll learn about something really cool: performing math using NumPy arrays. Imagine you have a magical box of numbers that you can use to do tricks. That is what NumPy can help you do. Let's dive in and make it enjoyable and simple to comprehend!
What is NumPy?
NumPy is a super aid that simplifies math with large numbers. Consider it your mathematical magic wand!
What are arrays?
An array is essentially a fancy term for a collection of numbers. Picture a row of toy vehicles lined up. Each car represents a number, and the entire row is an array.
Here's how to create an array using NumPy:
import numpy as np
# Creating an array of numbers
array1 = np.array([1, 2, 3, 4])
Now, let’s learn some magic tricks we can do with these numbers!
Trick 1: Adding Numbers
Adding numbers in an array is like putting more cars in your row.
array2 = np.array([5, 6, 7, 8])
# Adding the numbers in each spot
sum_array = array1 + array2 # This gives [6, 8, 10, 12]
Each number in the first array gets added to the number in the same spot in the second array. Simple, right?
Trick 2: Subtracting Numbers
Subtracting numbers is like taking away some cars.
# Subtracting the numbers in each spot
diff_array = array1 - array2 # This gives [-4, -4, -4, -4]
Each number in the first array has the number in the same spot in the second array taken away.
Trick 3: Multiplying Numbers
Multiplying numbers is like doubling or tripling your cars.
# Multiplying the numbers in each spot
product_array = array1 * array2 # This gives [5, 12, 21, 32]
Each number in the first array is multiplied by the number in the same spot in the second array.
Trick 4: Dividing Numbers
Dividing numbers is like splitting your cars into smaller groups.
# Dividing the numbers in each spot
quotient_array = array1 / array2 # This gives [0.2, 0.333, 0.428, 0.5]
Each number in the first array is divided by the number in the same spot in the second array.
Bonus Trick: Using One Number Everywhere
Sometimes, you want to do something to all your cars with just one number. This is called broadcasting.
# Using one number with an array
number = 2
broadcasted_array = number * array1 # This gives [2, 4, 6, 8]
Here, each car is multiplied by 2. It’s like giving each car a buddy!
Conclusion
So there you have it, little mathematician! NumPy allows you to do a variety of interesting and simple mathematical operations. NumPy makes addition, subtraction, multiplication, and division as simple as playing with your favorite toys. Continue exploring and having fun with your magic number tricks!