Professional Documents
Culture Documents
NUMPY Prog
NUMPY Prog
Write a NumPy program to test whether none of the elements of a given array is
zero.
import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Write a NumPy program to test if any of the elements of a given array is non-
zero.
import numpy as np
x = np.array([1, 0, 0, 0])
print("Original array:")
print(x)
print(np.any(x))
x = np.array([0, 0, 0, 0])
print("Original array:")
print(x)
print(np.any(x))
Write a NumPy program to create a vector with values from 0 to 20 and change
the sign of the numbers in the range from 9 to 15.
import numpy as np
x = np.arange(20)
print("Original vector:")
print(x)
print("After changing the sign of the numbers in the range from 9 to 15:")
print(x)
x = np.array([3, 5])
y = np.array([2, 5])
print("Original numbers:")
print(x)
print(y)
print("Comparison - greater")
print(np.greater(x, y))
print("Comparison - greater_equal")
print(np.greater_equal(x, y))
print("Comparison - less")
print(np.less(x, y))
print("Comparison - less_equal")
Write a NumPy program to create an array of all the even integers from 30 to 70.
import numpy as np
array=np.arange(30,71,2)
print("Array of all the even integers from 30 to 70")
print(array)
Write a NumPy program to create a vector with values ranging from 15 to 55 and
print all values except the first and last.
import numpy as np
v = np.arange(15,55)
print("Original vector:")
print(v)
print("All values except the first and last of the said vector:")
print(v[1:-1])
Write a NumPy program to sort a given array of shape 2 along the first axis, last
axis and on flattened array.
import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:")
print(a)
print(np.sort(a, axis=0))
print(np.sort(a))
print(np.sort(a, axis=None))
Write a NumPy program to create a structured array from given student name,
height, class and their data types. Now sort the array on height.
import numpy as np
data_type = [('name', 'S15'), ('class', int), ('height', float)]
print("Original array:")
print(students)
print("Sort by height")
print(np.sort(students, order='height'))
Write a NumPy program to create a structured array from given student name,
height, class and their data types. Now sort by class, then height if class are
equal.
import numpy as np
print("Original array:")
print(students)
print("Original array:")
print(nums)
print(np.partition(nums, 4))
print("Add:")
print(np.add(1.0, 4.0))
print("Subtract:")
print(np.subtract(1.0, 4.0))
print("Multiply:")
print(np.multiply(1.0, 4.0))
print("Divide:")
print(np.divide(1.0, 4.0))