Basic Array Operations in NumPy

Introduction to Basic Array Operations

Welcome! Let's explore Basic Array Operations with NumPy, a powerful library for data analysis, machine learning, and scientific computing. We'll seek answers to questions like: How can arrays interact with one another? Can they be added, subtracted, multiplied, and divided? And if so, what insights can we gain from these operations?

Overview of Basic Array Operations

"Basic Array Operations" refer to mathematical operations like addition, subtraction, multiplication, and division that are performed on arrays in an element-wise manner.

Consider two arrays representing yesterday's and today's temperatures. To find the change in temperature, you would subtract the yesterday array from the today array.

Ensure the arrays have the same shape before performing these operations!

NumPy Array Addition and Subtraction

In NumPy, the + and - operators perform addition and subtraction operations, respectively, between arrays in an element-wise fashion.

Let's say you have arrays of products sold in two consecutive months. To find the total sales, simply add the arrays:

import numpy as np

sales_month1 = np.array([120, 150, 90])
sales_month2 = np.array([130, 160, 80])
total_sales = sales_month1 + sales_month2
print(total_sales)  # Outputs: [250 310 170]

Similarly, to find the difference in sales, subtract one array from the other:

difference_sales = sales_month1 - sales_month2
print(difference_sales)  # Outputs: [-10 -10 10]

NumPy Array Multiplication and Division

Multiply or divide arrays using * and / operators in NumPy. They work element-wise as well.

Assume you have arrays of product prices and quantities sold. The total revenue can be found by multiplying:

import numpy as np

prices = np.array([20, 30, 50])
quantities = np.array([100, 200, 150])
revenue = prices * quantities
print(revenue)  # Outputs: [2000 6000 7500]

Similarly, you might have an array of total revenue for each product and an array of units sold. To find the price per unit, simply divide the total revenue by the number of units sold:

total_revenue = np.array([2000, 6000, 7500])
units_sold = np.array([100, 200, 150])
price_per_unit = total_revenue / units_sold
print(price_per_unit)  # Outputs: [20. 30. 50.]
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal