Articles

# Perform mathematical operations on numpy arrays

In this numpy tutorial, we will discuss how to perform:

• arithmetic operations in numpy arrays.

Before we learn about mathematical operations on numpy arrays, lets know basics about it.

numpy stands for numeric python which is used to perform mathematical operations on arrays.

It is a module in which we have to import from the python.

Syntax to import:

import numpy

We can also use alias for the module

For example,

import numpy as np

We can directly use np to call the numpy module.

Array

An array is an one dimensional data structure used to store single data type data.

I.E It will only store all integer data or all string type data.or all float type data.

We can create an numpy array by using array() function.

Syntax:

numpy.array(elements)

where, elements are the input data elements.

Lets see the methods provided to perform mathematical operations on numpy arrays.

### mathematical operations on numpy arrays

There are arithmetic functions available in numpy module to be performed on two numpy arrays. They are

Subtraction: Perform Subtraction on elements in two numpy arrays
numpy.sub(array1,array2)

Multiplication: Perform Multiplication on elements in two numpy arrays
numpy.multiply(array1,array2)

Division: Perform Division on elements in two numpy arrays
numpy.divide(array1,array2)

Power - raise a power for an elements in the numpy array
numpy.power(array,value)

where,

1. array1 is the first input numpy array

2. array2 is the second input numpy array

Examplemathematical operations on numpy arrays

Perform all arithmetic operations in numpy array or math operations on numpy arrays.

#importing the numpy module
import numpy

#create array with 5 integers
array_data1=numpy.array([10,20,30,50,78])

#create array with 5 integers
array_data2=numpy.array([1,2,3,4,5])

# display the arrays
print(array_data1,array_data2)

print()

print()

#perform subtraction
print("subtraction ",numpy.subtract(array_data1,array_data2))

print()

#perform multiplication
print("multiplication ",numpy.multiply(array_data1,array_data2))

print()

#perform division
print("division ",numpy.divide(array_data1,array_data2))

print()

#perform power raise to 3 for array1
print("power ",numpy.power(array_data1,3))

print()

#perform power raise to 5 for array2
print("power ",numpy.power(array_data2,5))

Outputmathematical operations on numpy arrays result

[10 20 30 50 78] [1 2 3 4 5]

addition  [11 22 33 54 83]

subtraction  [ 9 18 27 46 73]

multiplication  [ 10  40  90 200 390]

division  [10.  10.  10.  12.5 15.6]

power  [  1000   8000  27000 125000 474552]

power  [   1   32  243 1024 3125]

This wraps up our session on mathematical operations on numpy arrays or math operations on numpy arrays.

Numpy

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com