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?
"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!
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:
Python1import numpy as np 2 3sales_month1 = np.array([120, 150, 90]) 4sales_month2 = np.array([130, 160, 80]) 5total_sales = sales_month1 + sales_month2 6print(total_sales) # Outputs: [250 310 170]
Similarly, to find the difference in sales, subtract one array from the other:
Python1difference_sales = sales_month1 - sales_month2 2print(difference_sales) # Outputs: [-10 -10 10]
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:
Python1import numpy as np 2 3prices = np.array([20, 30, 50]) 4quantities = np.array([100, 200, 150]) 5revenue = prices * quantities 6print(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:
Python1total_revenue = np.array([2000, 6000, 7500]) 2units_sold = np.array([100, 200, 150]) 3price_per_unit = total_revenue / units_sold 4print(price_per_unit) # Outputs: [20. 30. 50.]
The dot product is the sum of the product of corresponding elements in arrays. It is widely used in math and data analysis.
Python1import numpy as np 2 3array1 = np.array([1, 2, 3]) 4array2 = np.array([4, 5, 6]) 5dot_product = np.dot(array1, array2) 6print(dot_product) # Outputs: 32 (1 * 4 + 2 * 5 + 3 * 6 = 32)
Today, we've explored NumPy
's Basic Array Operations, which are fundamental for tasks such as data analysis and machine learning. We've performed addition, subtraction, multiplication, and division operations on arrays, reshaped and combined arrays, and computed the dot product of two arrays.
Now, let's tackle some practice exercises to solidify these concepts!