Python programs using NumPy
NumPy in Python a vast library for the Python programmers and users. By providing a large collection of high-level mathematical functions to operate arrays and matrices and many more.
Some example programs using NumPy in Python
To know more about NumPy math functions: Mathematical Functions In Numpy
Python program to check the NumPy version in any system-
import numpy as npcheck print(npcheck.__version__)
Write a Python program to create a 3×3 matrix with values ranging from 2 to 10.
import numpy as np
x = np.array([1,2,3,4,5,6,7,8,9,100,20,30,45,30])
print ("max=",x.max(),"min=",x.min(),"mean=",x.mean(),"var=",x.var())Output-
max= 100 min= 1 mean= 19.285714285714285 var= 664.4897959183675
Python program to multiply all values in the list using numpy.prod()-
import numpy
list1 = [1, 2, 3]
list2 = [3, 2, 4]
# using numpy.prod() to get the multiplications
result1 = numpy.prod(list1)
result2 = numpy.prod(list2)
print("List 1=",result1)
print("List 2=",result2)
Output-
List 1= 6 List 2= 24
Second Method-
from functools import reduce
list1 = [1, 2, 3]
list2 = [3, 2, 4]
result1 = reduce((lambda x, y: x * y), list1)
result2 = reduce((lambda x, y: x * y), list2)
print("list 1=",result1)
print("list 2=",result2)
Output-
list 1= 6 list 2= 24
Write a Python program to create a 3×3 matrix-
import numpy as np x = np.arange(2, 11).reshape(3,3) print(x)
Output-
[[ 2 3 4] [ 5 6 7] [ 8 9 10]]
Python program to reverse an array-
import numpy as np
x = np.arange(12, 38)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x)Output-
Original array: [12 13 14 15 16 17 18 19] Reverse array: [19 18 17 16 15 14 13 12]
Python program to append values to the end of an array-
import numpy as npappend
x = [100, 200, 300]
print("Original array:")
print(x)
x = npappend.append(x, [[400, 500, 610], [700, 810, 900]])
print("After append the values are:")
print(x)Output-
Original array: [100, 200, 300] After append array be like: [100 200 300 400 500 610 700 810 900]
Python program to append values to start and the end of an array-
import numpy as np
x = [100, 200, 300]
print("Original array:")
print(x)
x = np.append([400, 500, 600],x)
x1=np.append(x,[700,800,900])
print("After appending values:")
print(x1)
Output-
Original array: [100, 200, 300] After append values array will be like: [400 500 600 100 200 300 700 800 900]
Python program for checking the unique elements of an array-
import numpy as np
x = np.array([10, 10, 20, 20, 30, 30])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x))
x = np.array([[1, 1], [2, 3]])
print("Original array:")
print(x)
print("Unique elements of the above array:")
print(np.unique(x))
Output-
Original array: [10 10 20 20 30 30] Unique elements of the above array: [10 20 30] Original array: [[1 1] [2 3]] Unique elements of the above array: [1 2 3]
Leave a Reply