import numpy as np
# Creating a 1-dimensional array
= np.array([1, 2, 3, 4, 5])
arr_1d print('1D Array:', arr_1d)
# Creating a 2-dimensional array
= np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr_2d print('\n2D Array:')
print(arr_2d)
# Creating a 3-dimensional array
= np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
arr_3d print('\n3D Array:')
print(arr_3d)
Introduction to NumPy
NumPy, which stands for Numerical Python, is a foundational package for numerical computations in Python. It provides support for large multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
Installation
To install NumPy, you can use the package manager pip
:
!pip install numpy
Importing NumPy
Once installed, you can import the NumPy library using the following command:
import numpy as np
By convention, numpy
is usually imported as np
.
Examples of NumPy Arrays
In NumPy, arrays are the main way to store and manipulate data. Let’s look at some examples of creating and working with arrays.
Array Operations
Arrays in NumPy can be operated on in a variety of ways. One common operation is element-wise addition. Let’s see what happens when we try to add arrays of different shapes.
# Adding two 1D arrays of the same shape
= np.array([1, 2, 3])
arr1 = np.array([4, 5, 6])
arr2 = arr1 + arr2
sum_1d print('Sum of two 1D arrays:', sum_1d)
# Adding two 2D arrays of the same shape
= np.array([[1, 2], [3, 4]])
arr3 = np.array([[5, 6], [7, 8]])
arr4 = arr3 + arr4
sum_2d print('\nSum of two 2D arrays:')
print(sum_2d)
# Trying to add arrays of different shapes (This will raise an error)
try:
= arr1 + arr3
sum_diff_shapes except ValueError as e:
print('\nError when trying to add arrays of different shapes:', e)
NumPy Functions and Attributes
NumPy provides a wide range of functions and attributes to perform operations on arrays. Let’s explore some of the commonly used ones.
# Sample array for demonstration
= np.array([1, 5, 3, 7, 2, 8, 4, 6])
arr
# logical_and and logical_or
= np.logical_and(arr > 2, arr < 7)
condition_and = np.logical_or(arr < 3, arr > 6)
condition_or print('logical_and result:', condition_and)
print('logical_or result:', condition_or)
# .shape attribute
print('\nShape of the array:', arr.shape)
# argmin() and argmax()
print('\nIndex of minimum value:', arr.argmin())
print('Index of maximum value:', arr.argmax())
# mean, median, std, var
print('\nMean of the array:', np.mean(arr))
print('Median of the array:', np.median(arr))
print('Standard deviation of the array:', np.std(arr))
print('Variance of the array:', np.var(arr))
# percentile
print('\n25th percentile:', np.percentile(arr, 25))
print('75th percentile:', np.percentile(arr, 75))
Explanation of the functions and attributes used:
logical_and
: This function performs element-wise logical AND operation. It returns an array of the same shape as the input arrays, withTrue
where the condition is met andFalse
otherwise.logical_or
: Similar tological_and
, this function performs element-wise logical OR operation..shape
: This attribute returns a tuple representing the dimensions of the array.argmin()
: Returns the index of the minimum value in the array.argmax()
: Returns the index of the maximum value in the array.mean
: Computes the arithmetic mean of the array elements.median
: Returns the median of the array elements.std
: Computes the standard deviation of the array elements.var
: Computes the variance of the array elements.percentile
: Computes the specified percentile of the array elements.
Additional NumPy Functions
NumPy offers a plethora of functions for various mathematical and statistical operations. Here are some more functions that haven’t been covered yet:
dot
: Computes the dot product of two arrays.cross
: Computes the cross product of two arrays.linspace
: Returns evenly spaced numbers over a specified range.arange
: Returns evenly spaced values within a given interval.reshape
: Gives a new shape to an array without changing its data.concatenate
: Joins two or more arrays along an existing axis.split
: Divides an array into multiple sub-arrays.sin
,cos
,tan
: Trigonometric functions.exp
: Computes the exponential of all elements in the input array.log
,log10
,log2
: Natural logarithm, base-10 logarithm, and base-2 logarithm.sqrt
: Returns the non-negative square-root of an array, element-wise.unique
: Finds the unique elements of an array.sort
: Returns a sorted copy of an array.
# Sample arrays for demonstration
= np.array([1, 2, 3])
a = np.array([4, 5, 6])
b
# dot
= np.dot(a, b)
dot_product print('Dot product of a and b:', dot_product)
# cross
= np.cross(a, b)
cross_product print('\nCross product of a and b:', cross_product)
# linspace
= np.linspace(0, 10, 5)
linspace_array print('\nLinspace array:', linspace_array)
# arange
= np.arange(0, 10, 2)
arange_array print('\nArange array:', arange_array)
# reshape
= np.arange(9).reshape(3, 3)
reshaped_array print('\nReshaped array:')
print(reshaped_array)
# concatenate
= np.concatenate((a, b))
concatenated_array print('\nConcatenated array:', concatenated_array)
# split
= np.split(concatenated_array, 2)
split_arrays print('\nSplit arrays:', split_arrays)
# sin, cos, tan
print('\nSin of a:', np.sin(a))
print('Cos of a:', np.cos(a))
print('Tan of a:', np.tan(a))
# exp
print('\nExponential of a:', np.exp(a))
# log, log10, log2
print('\nNatural logarithm of a:', np.log(a))
print('Base-10 logarithm of a:', np.log10(a))
print('Base-2 logarithm of a:', np.log2(a))
# sqrt
print('\nSquare-root of a:', np.sqrt(a))
# unique
= np.unique(np.array([1, 2, 2, 3, 3, 3]))
unique_array print('\nUnique elements:', unique_array)
# sort
= np.sort(np.array([3, 1, 2]))
sorted_array print('\nSorted array:', sorted_array)
Exercises
To test your understanding of the concepts covered in this notebook, try out the following exercises:
Easy
Array Creation: Create a 1-dimensional NumPy array containing the numbers from 1 to 10.
Array Reshaping: Take the array you created in the previous exercise and reshape it into a 2x5 matrix.
Medium
Array Operations: Given two arrays
a = np.array([1, 2, 3, 4])
andb = np.array([5, 6, 7, 8])
, compute the dot product and the element-wise sum.Array Functions: For the array
c = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
, compute the mean, median, and standard deviation. Also, find the 25th and 75th percentiles.
Hard
- Logical Operations: Given the array
d = np.array([3, 7, 1, 10, 5, 8, 2, 9, 4, 6])
, use logical operations to find all numbers in the array that are greater than 3 and less than 8. Then, compute the sum of these numbers.