By: Rajendra Gupta | Updated: 2024-12-12 | Comments | Related: > Python
Problem
Python is enriched with various libraries with built-in functions for various scientific computations. NumPy is one of the popular and widely used libraries. Do you know how to install NumPy and use its functions with multi-dimensional arrays? If not, let's check out NumPy together in this NumPy tutorial.
Solution
NumPy, aka Numerical Python, works well with multi-dimensional arrays and matrices enabling users to perform quick and efficient numerical computations. A few key features of NumPy are:
- Is an open source module.
- Supports homogenous multi-dimensional arrays.
- Supports data science machine learning computations for data analysis manipulations.
- Integrates with Python libraries such as SciPy and Pandas.
- Requires users to perform complex tasks using its built-in functions with few lines of code. Its mathematic functions include linear algebra, Fourier transforms, matrix operations (sum, multiplications), etc.
- Is memory efficient for handling large datasets. It supports indexing and slicing techniques to work with the relevant data.
To install NumPy in Python, we can run the pip command -
pip install numpy
, as shown
below.
Usually, it is best practice to import the NumPy module with the popular shortcut np for code readability:
import numpy as np
Now, we can use the Numpy modules with np alias as np.<function\object>. You do not need to import it by calling every module. You can import it once and use it subsequently in the same Python file\session.
Let's explore the NumPy module functions with various examples.
Exploring Single and Two-dimensional NumPy Array
A Python NumPy array can store multiple homogenous values. A NumPy array can be n-directional, such as a one-dimensional or two-dimensional array.
NumPy Array Examples
Description | Sample Syntax and Output |
---|---|
One-dimensional array Function: np.array() |
my1darray = np.array([15.9,16.9,17.9]) print(my1darray) |
Two-dimensional array |
my2darray = np.array([[101, 202, 303], [404, 505, 606], [707, 808, 909]]) print(my2darray) |
Create a NumPy array |
num1 = [100,989,6589] array1= np.array(num1) print(array1) |
Three-dimensional array |
arr3d = np.array([[[1.1, 2.2, 3.3, 4.4], [5.5, 6.6, 7.7, 8.8], [9.9, 10.10, 11.11, 12.12]], [[13.13, 14.14, 15.15, 16.16], [17.17, 18.18, 19.19, 20.20], [21.21, 22.22, 23.23, 24.24]]]) print(arr3d) |
Create a 1D array and initialize it with zeros. Function: np.zeros() |
ar1 = np.zeros(4) print(ar1) |
Create a 2D array and initialize it with zeros Function: np.zeros() |
ar2= np.zeros((3,4)) print(ar2) [0. 0. 0. 0.] [0. 0. 0. 0.]] |
Create a 1D array and initialize it with ones Function: np.ones() |
ar3= np.ones(5) print(ar3) |
Initialize the array within a specified number interval Function: np.arange() |
array1 = np.arange(10) print("Using np.arange(10):", array1) |
Use the starting, step and end of interval value in the array Function: np.arrange() |
#start value 2 #step value 2 #End value 20 array1 = np.arange(2,20,2) print(array1) |
Using the negative starting value in the np.arrange() |
print(np.arange(-3, 3, 0.5)) |
Create an array of evenly numbered sample values Function: np.linspace() |
print( np.linspace(0,2,9) ) |
Create an array with random numbers. Function: np.random.rand() Default Data Type: Float |
print( np.random.rand(7)) |
Create an integer array 1D with random numbers Function: np.random.randint() |
#total number of elements 5 #Lowest value 1 #Highest value 10 print( np.random.randint(1, 10, size=5)) |
Create an integer array 2D with random numbers Function: np.random.randint() |
#array dimensions 4 *4 #Lowest value 0 #Highest value 50 random2darray = np.random.randint(0, 50, size=(4, 4)) print(random2darray) [22 42 40 38] [34 18 1 25] [27 13 34 41]] |
Create an empty array Function: np.empty() #does not initialize the array |
earray = np.empty(5) print(earray _array) |
Create an array and initialize it with a constant value. Function np.full() |
# array dimension 2*2 #Constant value 7 a = np.full((2,2),7) print(a) [7 7]] |
Creates a 2D array with ones on the diagonal and zeros Function: np.eye() |
f = np.eye(5) print(f) [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]] |
NumPY Q&A
Question | Answer | Sample Syntax |
---|---|---|
What is the function to identify the array dimension? | Ndim |
arr1d = np.array([1, 2, 3, 4, 5]) print(arr1d.ndim) Output: 1 arr2d = (np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) print(arr2d.ndim) Output: 2 |
How do you find the total number of elements in a given array? | Size |
print(arr1d.size) Output: 5 print(arr2d.size) Output: 9 |
How do you check the data type of the NumPy array? | Dtype |
print(arr1d.dtype) Output: int64 arrfloat = np.array([1, 2, 3, 4, 5], dtype=float) Output: float64 |
How do you get the size of an array in each dimension? | Shape |
print(arr1d.shape) Output: (2,) Print(arr_2d.shape) Output : (3,3) arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]) print( arr3d.shape) Output : (3,2,2) |
Can we use string or mix data types in the NumPy array? | We can store strings or mix data types in a NumPy array. |
arrm = np.array([1, 2.5, 'apple']) print(arrm.dtype) Output: <U32 # NumPy converts all elements to strings because of the mixed data types. # We can use dtype as an object to store strings, integers, floats, etc. This is known as a Structured array arrt = np.array([1, 2.5, 'apple'], dtype=object) print(arrt.dtype) Output: object #Another way is to define the object types with different columns in an array. dtype = np.dtype([('id', np.int32), ('name', np.str_, 20), ('age', np.int32), ('active_or_inactive', np.str_, 20)]) emp = np.array([(1, 'Rajendra', 32, 'active'), (2, 'Mohan', 45, 'active'), (3, 'John', 60, 'inactive'), 4, 'Nikhil', 52, 'active')], dtype=dtype) print(emp) Output: [(1, 'Rajendra', 32, 'active') (2, 'Mohan', 45, 'active') (3, 'John', 60, 'inactive') (4, 'Nikhil', 52, 'active')] |
Using NumPy to Perform Various Mathematical Operations
As discussed earlier, we can perform mathematical operations using built-in mathematical functions. These functions can be categorize into the following categories:
- Arithmetic
- Trigonometry
- Exponential
- Statistical
Let's explore these functions with various examples.
Operation | Sample Syntax and Output |
---|---|
Addition Operator + |
a1 = np.array([10, 20, 30]) b1 = np.array([2, 5, 10]) print(a1+b1) |
Subtraction Operator - |
print(a1-b1) |
Multiplication Operator * |
print (a1*b1) |
Division Operator / |
print (a1/b1) |
Adding values to each element of an array Operator += |
arr1 = np.array([11, 22, 33, 44, 55]) arr1 += 10 print(arr1) |
Subtract values for each element of an array Operator -= |
arr1 -= 1 print(arr1) |
Multiply values of each element of an array Operator *= |
arr1 *= 2 print(arr1) |
Find the Minimum number from a NumPy array Operator: np.min() |
arr1 = np.array([100, 20585,98999,47]) print(np.min(arr1)) |
Find the Maximum number from a NumPy array Operator: np.max() |
print(np.max(arr1)) |
Find the Mean value from the NumPy array Operator: np.median() |
print(np.median(arr1)) |
Find standard deviation Operator: np.std() |
print(np.std(arr1)) |
Multiply two matrixes Operator: Np.dot() |
m1 = np.array([[11, 66], [31, 47]]) m2 = np.array([[59, 65], [17, 98]]) r = np.dot(m1, m2) print(r) |
Transposing an array Operator: np.transpose() |
m1 = np.array([[4, 6], [2, 9], [14, 6]]) t= m1.transpose() print(t) Transposed array [[ 4 2 14] [ 6 9 6]] |
Calculate the sine of an angle Operator: np.sin() |
angles = np.array([0, 1, 2]) sine_values = np.sin(angles) print(sine_values) |
Convert the angle to degrees Operator: np.degrees() |
angle_degree = np.degrees(angles) print(angle_degree) |
Convert the angle back to radians Output: np.radian() |
angle_radian = np.radians(angle_degree) print(angle_radian) |
Round the value to the desired precision in the NumPy array Operator: np.round() |
n1 = np.array([6.23456, 9.34567, 13.45678, 78.56789]) np.round(n1,2) |
Get the nearest integer that is less than each element in an array Operator: np.floor() |
print(np.floor(n1)) |
Get the nearest integer that is less than each element in an array Operator: np.ceil() |
print(np.ceil(n1)) |
Next Steps
- Stay tuned for Python tutorials in the upcoming tips.
- Explore more Python programming tips on MSSQLTips:
About the author
This author pledges the content of this article is based on professional experience and not AI generated.
View all my tips
Article Last Updated: 2024-12-12