
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Arithmetic Operations
NumPy Arithmetic Operations
NumPy makes performing arithmetic operations on arrays simple and easy. With NumPy, you can add, subtract, multiply, and divide entire arrays element-wise, meaning that each element in one array is operated on by the corresponding element in another array.
When performing arithmetic operations with arrays of different shapes, NumPy uses a feature called broadcasting. It automatically adjusts the shapes of the arrays so that the operation can be performed, extending the smaller array across the larger one as needed.
Basic NumPy Arithmetic Operations
NumPy provides several arithmetic operations that are performed element-wise on arrays. These include addition, subtraction, multiplication, division, and power.
NumPy Array Addition
Addition in NumPy is performed element-wise. When two arrays of the same shape are added, corresponding elements are summed together. Broadcasting rules apply when arrays have different shapes −
import numpy as np # Creating two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Adding arrays result = a + b print(result)
Following is the output obtained −
[5 7 9]
NumPy Array Subtraction
Subtraction in NumPy is also element-wise. Subtracting two arrays with the same shape returns an array where each element is the difference of the corresponding elements in the input arrays −
import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) # Subtracting arrays result = a - b print(result)
This will produce the following result −
[ 9 18 27]
NumPy Array Multiplication
Element-wise multiplication is performed using the * operator in NumPy. When multiplying arrays, each element of the first array is multiplied by the corresponding element in the second array −
import numpy as np # Creating two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Multiplying arrays result = a * b print(result)
Following is the output of the above code −
[ 4 10 18]
NumPy Array Division
Division is performed element-wise using the / operator in NumPy. It results in an array where each element is the quotient of the corresponding elements in the input arrays −
import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([1, 2, 5]) # Dividing arrays result = a / b print(result)
The output obtained is as shown below −
[10. 10. 6.]
NumPy Array Power Operation
The power operation is performed element-wise using the ** operator in NumPy. Each element of the base array is raised to the power of the corresponding element in the exponent array −
import numpy as np # Creating two arrays a = np.array([2, 3, 4]) b = np.array([1, 2, 3]) # Applying power operation result = a ** b print(result)
After executing the above code, we get the following output −
[ 2 9 64]
We can also use the numpy.power() function to raise elements of an array to the specified power. This function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array −
import numpy as np a = np.array([10,100,1000]) print ('Our array is:') print (a) print ('\n') print ('Applying power function:') print (np.power(a,2)) print ('\n') print ('Second array:') b = np.array([1,2,3]) print (b) print ('\n') print ('Applying power function again:') print (np.power(a,b))
It will produce the following output −
Our array is: [ 10 100 1000] Applying power function: [ 100 10000 1000000] Second array: [1 2 3] Applying power function again: [ 10 10000 1000000000]
Advanced NumPy Arithmetic Operations
Advanced arithmetic operations in NumPy include operations such as modulo, floor division, and power. These operations handle more complex mathematical tasks and are performed element-wise, similar to basic arithmetic operations, but with additional functionality for modular arithmetic and exponentiation.
NumPy Modulo Operation
The modulo operation is performed using the % operator in NumPy. When applied to arrays, it operates element-wise, meaning each element of the first array is divided by the corresponding element in the second array, and the remainder is calculated −
import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([3, 7, 8]) # Applying modulo operation result = a % b print(result)
The result produced is as follows −
[1 6 6]
We can also use the numpy.mod() function to calculate the element-wise remainder of division (modulus operation) between the elements of two arrays or between an array and a scalar.
This function returns the remainder when one array is divided by another array or scalar, applying the modulus operation element by element.
import numpy as np a = np.array([10,20,30]) b = np.array([3,5,7]) print ('First array:') print (a) print ('\n') print ('Second array:') print (b) print ('\n') print ('Applying mod() function:') print (np.mod(a,b)) print ('\n') print ('Applying remainder() function:') print (np.remainder(a,b))
Following is the output of the above code −
First array: [10 20 30] Second array: [3 5 7] Applying mod() function: [1 0 2] Applying remainder() function: [1 0 2]
NumPy Floor Division
The floor division in NumPy is performed element-wise using the // operator. It returns the largest integer less than or equal to the division result −
import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([3, 7, 8]) # Applying floor division result = a // b print(result)
We get the output as shown below −
[3 2 3]
NumPy Arithmetic Operations with Broadcasting
Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes by virtually expanding the smaller array to match the shape of the larger array.
Scalar and Array Operations in NumPy
When a scalar is used with an array, broadcasting expands the scalar to match the shape of the array, allowing element-wise operations −
import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Scalar value scalar = 10 # Adding scalar to array result = a + scalar print(result)
Following is the output obtained −
[[11 12 13] [14 15 16]]
Array with Different Shapes in NumPy
When two arrays of different shapes are used in NumPy, broadcasting aligns their shapes according to broadcasting rules −
import numpy as np # Creating arrays with different shapes a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) # Adding arrays result = a + b print(result)
This will produce the following result −
[[11 22 33] [14 25 36]]
NumPy Aggregation Functions
Aggregation functions in NumPy perform operations like sum, mean, min, and max across arrays, often using broadcasting to handle arrays of different shapes.
NumPy Sum Operation
The NumPy sum operation calculates the sum of array elements over a specified axis or over the entire array if no axis is specified. −
import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Summing elements result = np.sum(a) print(result) # Summing along axis 0 (columns) result_axis0 = np.sum(a, axis=0) print(result_axis0) # Summing along axis 1 (rows) result_axis1 = np.sum(a, axis=1) print(result_axis1)
Following is the output of the above code −
21 [5 7 9] [ 6 15]
NumPy Mean Operation
The NumPy mean operation calculates the average (arithmetic mean) of array elements over a specified axis or over the entire array −
import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Mean of elements result = np.mean(a) print(result) # Mean along axis 0 (columns) result_axis0 = np.mean(a, axis=0) print(result_axis0) # Mean along axis 1 (rows) result_axis1 = np.mean(a, axis=1) print(result_axis1)
The output obtained is as shown below −
3.5 [2.5 3.5 4.5] [2. 5.]
NumPy Array Operations with Complex Numbers
The following functions are used to perform operations on array with complex numbers.
numpy.real(): Returns the real part of the complex data type argument.
numpy.imag(): Returns the imaginary part of the complex data type argument.
numpy.conj(): Returns the complex conjugate, which is obtained by changing the sign of the imaginary part.
numpy.angle(): Returns the angle of the complex argument. The function has degree parameter. If true, the angle in the degree is returned, otherwise the angle is in radians.
Example
In the following example, we are using NumPy functons: real(), imag(), conj() and angle() to perform operations on array with complex numbers −
import numpy as np a = np.array([-5.6j, 0.2j, 11. , 1+1j]) print ('Our array is:') print (a) print ('\n') print ('Applying real() function:') print (np.real(a)) print ('\n') print ('Applying imag() function:') print (np.imag(a)) print ('\n') print ('Applying conj() function:') print (np.conj(a)) print ('\n') print ('Applying angle() function:') print (np.angle(a)) print ('\n') print ('Applying angle() function again (result in degrees)') print (np.angle(a, deg = True))
It will produce the following output −
Our array is: [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ] Applying real() function: [ 0. 0. 11. 1.] Applying imag() function: [-5.6 0.2 0. 1. ] Applying conj() function: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ] Applying angle() function: [-1.57079633 1.57079633 0. 0.78539816] Applying angle() function again (result in degrees) [-90. 90. 0. 45.]
Basic Array Operations
Several routines are available in NumPy package for operations of elements in array. NumPy arrays support operations like additions, subtraction and indexing for efficient data manipulation −
Sr.No. | Operation & Description |
---|---|
1 |
numpy.add()
Enables efficient element-wise addition for data manipulation. |
2 |
numpy.subtract()
Computes element-wise differences between two arrays efficiently. |
3 |
numpy.multiply()
Computes element-wise products between two arrays efficiently. |
4 |
numpy.divide()
Performs element-wise division, requiring non-zero, same-shaped arrays. |
5 |
numpy.power()
Raises elements of one array to another's element-wise. |
6 |
numpy.mod()
Computes element-wise remainders of division between two arrays. |
7 |
numpy.remainder()
Computes element-wise remainders of division between two arrays. |
8 |
numpy.divmod()
Returns a tuple with quotient and remainder of division. |
7 |
numpy.abs()
Returns the positive absolute value of numbers. |
8 |
numpy.absolute()
Computes the absolute value of each array element efficiently. |
9 |
numpy.fabs()
Returns the positive magnitudes. |
10 |
numpy.sign()
Returns an element-wise indication of the sign of a number. |
11 |
numpy.conj()
Returns the complex conjugate, element-wise. |
12 |
numpy.exp()
Calculates the exponential of all elements in the input array. |
13 |
numpy.expm1()
Calculates exp(x)-1 for all elements in the array. |
14 |
numpy.log()
Natural logarithm, element-wise. |
15 |
numpy.log1p()
Computes element-wise natural logarithm of (1 + input array). |
16 |
numpy.log2()
Base-2 logarithm of x. |
17 |
numpy.log10()
Returns the base 10 logarithm of the input array, element-wise. |
18 |
numpy.sqrt()
Returns the non-negative square-root of an array, element-wise. |
19 |
numpy.square()
Returns the element-wise square of the input. |
20 |
numpy.cbrt()
Returns the cube-root of an array, element-wise. |
21 |
numpy.reciprocal()
Calculates the reciprocal of each element in arrays. |