Numpy Interview Questions and Answers

Q. 1 – What is Numpy?

The numpy is a module which is responsible for effectively storing and processing data at a faster rate as compared to normal array. The advantage of numpy is support of large number of in built mathematical operations as compared to other programming languages. Also, the support to represent n dimensions is also possible with numpy.

Q. 2 – How to Install Numpy?

As numpy is an external Python module, that’s why you need to use pip to install it. Just write python3 -m pip install numpy on terminal/Command line of your PC, this will download as well install numpy.

Q. 3 – How to create Single dimension numpy array?

import numpy as np
list1 = [1, 2.5, 8, 0, 1]
arr1 = np.array(list1)
print(arr1)                  # Prints out [1.  2.5 8.  0.  1. ]

Q. 4 – What attributes are provided by numpy?

  • ndim => As numpy provides n dimensions, we can get how many dimensions currently the array is having with ndim.
  • shape => Indicates number of rows and columns which again can be in different dimensions.
  • dtype => Indicates data type of elements stored in numpy.
import numpy as np
ip = [[1, 2, 3, 4], [5, 6, 7, 8]]
numpy_array = np.array(ip)
print(numpy_array)
print("Number of Dimensions in Numpy array are =>", numpy_array.ndim)
print("Shape of Numpy array is =>", numpy_array.shape)
print("Data Types in Numpy array are =>", numpy_array.dtype)

Output of Above Code

[[1 2 3 4]
 [5 6 7 8]]
Number of Dimensions in Numpy array are => 2
Shape of Numpy array is => (2, 4)
Data Types in Numpy array are => int64

Q. 5 – What utility methods are provided by numpy for creating different elements?

  • np.zeros() => Creates a numpy array only having zeros as elements. For example – np.zeros((3, 3)) creates a three-by-three dimensional numpy array just containing zeros only.
  • np.ones() => Creates a numpy array only having ones as elements. For example – np.ones((4, 4)) creates a four-by-four dimensional numpy array just containing ones only.
  • np.eye() => Creates a numpy array having ones at diagonals and zeros elsewhere. For example – np.eye(4, 5) will creates a four-by-five dimensional numpy array having ones at diagonals, zeros elsewhere.
  • np.arange() => Create a single or n dimension array in which numbers are populated starting from 0 to the number specified as parameter. For example – np.arange(7) will be returns array([0, 1, 2, 3, 4, 5, 6])

Q. 6 – Explain various simple mathematical operations which can be done on numpy?

import numpy as np
numpy_array1 = np.array([[1., 2., 3.],[4., 5., 6.]])
numpy_array2 = np.array([[2., 3., 4.], [4., 5., 6.]])

print("Adding two numpy arrays")
print(numpy_array1 + numpy_array2)
print("\n")

print("Subtracting two numpy arrays")
print(numpy_array1 - numpy_array2)
print("\n")

print("Reversing a numpy array")
print(1 / numpy_array1)
print("\n")

print("Reversing a numpy array")
print(1 / numpy_array2)
print("\n")

print("Taking under root of numpy array")
print(numpy_array1 ** 0.5)

Output of Above Code

Adding two numpy arrays
[[ 3.  5.  7.]
 [ 8. 10. 12.]]


Subtracting two numpy arrays
[[-1. -1. -1.]
 [ 0.  0.  0.]]


Reversing a numpy array
[[1.         0.5        0.33333333]
 [0.25       0.2        0.16666667]]


Reversing a numpy array
[[0.5        0.33333333 0.25      ]
 [0.25       0.2        0.16666667]]


Taking under root of numpy array
[[1.         1.41421356 1.73205081]
 [2.         2.23606798 2.44948974]]

Q. 7 – How to Transposing a Numpy Array?

Numpy array can be transposed by numpy_array.T code statement.

import numpy as np
numpy_array1 = np.array([[1., 2., 3.],[4., 5., 6.]])
print(numpy_array1.T)

Output of Above Code

[[1. 4.]
 [2. 5.]
 [3. 6.]]

Q. 12 – Explain various functions available in Numpy?

FunctionWhat does it do?
adsReturn absolute value element-wise
sqrtSquare root of each element is calculated
squareSquare of each element is calculated
expExponent ex of each element is calculates
signSign of each element – 1(postive), 0(zero), -1(negative) is calculates
ceilDetermines the ceiling value of each element
floorDetermines the floor of each element
rintRound elements to the nearest integer, preserving the dtype
modfReturn fractional and integral parts of given input
isnanReturns true if the value is NaN else false
isfinite, isinfReturn true indicating whether each element is finite or infinite

Q. 13 – What is Broadcasting in Numpy?

Ability of numpy to treat arrays with different dimensions or shape in a uniform way is called Brodcasting.

import numpy as np

x = np.array([[1], [2], [3]])

y = np.array([4, 5, 6])

b = np.array(y, x)

for t in b:
	print(t)

Output of Above Code

(4, 1)
(5, 1)
(6, 1)
(4, 2)
(5, 2)
(6, 2)
(4, 3)
(5, 3)
(6, 3)

Q. 14 – Explain rules of Broadcasting in Numpy?

  • Whenever two arrays have different dimensions the shape of the one with fewer dimensions is adjusted by padding with ones on ite leading left side.
  • If there is a difference in the shape of the two arrays, it does not match in any dimension, then dimension is strected to match the other shape for that array with shape one.
  • An error is raised in case the dimension and sizes disagree, and neither is equal to 1.

Q. 15 – Explain functions available in numpy.linalg?

Function in numpy.linalgWhat does it do?
dot(a, b)Dot product of two arrays
vdot(a, b)Return dot product of two vectors
linalg.multi_dot(arrays)Compute dot product of two or more arrays in a single function call
while automatically selecting the fastest evaluation order
inner(a, b)Inner product of two arrays
outer(a, b)Computer the outer product of two vectors
matmul(a, b)Matrix product of two arrays
tensordot(a, b)Computer tensor dot product along specified axes for arrays >= 1 – D
einsum(subscripts, *operands)Evaluates Einstein summation convention on the operands
linalg.matrix_power(M, n)Raise a square matric to the integer power n
kron(a, b)Kronecker product of two arrays
linalg.cholesky(a)Cholesky decomposition
linalg.qr(a[, mode])Computer the qr factorization of a matric
linalg.svd(a[, full_matrices, computer_uv])Singular value decomposition
linalg.eig(a)Computer the eigenvalues and right eigenvectors of a square array
linalg.eigh(a[, UPLO])Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix
linalg.eigvals(a)Computer the eigenvalues of a general matrix
linalg.eigvalsh(a[, UPLO])Computer the eigenvalues of a Hermitian or real symmetric matrix
linalg.norm(x[, ord, axis, keepdims])Matric or vector norm
linalg.cond(x[, p])Computer the condition number of a matrix
linalg.det(a)Computer the determinant of an array
linalg.matrix_rank(M[, tol])Return matrix rank of array using SVD method
linalg.slogdet(a)Computer the sign and natural logarithm of the determinant of an array
trace(a[, offset, axis1, axis2, dtype, out])Return the sum along diagonals of the array
linalg.solve(a, b)Solve a linear matrix equation, or system of linear scalar equations
linalg.tensorsolve(a, b[, axes])Solve the tensor equation ax = b for x
linalg.lstsq(a, b[, rcond])Return the least-squares solution to a linear scalar equations
linalg.inv(a)Compute the multiplicative inverse of a matrix
linalg.pinv(a[, rcond])Computer the Moore-Penrose pseudo-inverse of a matrix
linalg.tensorinv(a[, ind])Computer the inverse of an N-dimensional array

Q. 16 – How to save numpy data from memory to flat file?

Numpy data can be stored into memory in two files format – .npy file or .text file. For storing data as .npy file, just use np.save(‘output_file_name’, numpy_object) and for storing data as .txt file numpy function np.savetxt(‘output_file_name’, numpy_object).

  • np.save(‘output_file_name’, numpy_object) saves numpy_object data as .npy file
  • np.savetxt(‘output_file_name’, numpy_object) saves numpy_object data as .txt file

Below is the sample code showing saving of data into different types of files in Numpy.

import numpy as np

a = np.array([1, 2, 3, 4, 5])

np.save('output_file_name', a)
# Saving a array data as .npy file


b = np.savetxt('output_file_name', a)
# Saving a array data as .txt file

Q. 17 – What is the use of where keyword in Numpy?

where keyword in Numpy can be used for data matching based upon some condition.

Image showing use of keyword "where" in Numpy

Q. 18 – What is the use of extract keyword in Numpy?

extract keyword in Numpy can be used for applying a condition to some specific data

Image showing use of keyword "extract" in Numpy

Q. 19 – What is use of ndenumerate?

ndenumerate return the co-ordinates and corresponding values in the co-ordinates

import numpy as np

A = np.array([[11, 22], [33, 43]])
for index, x in np.ndenumerate(A):
	print(index, x)

Output of Above Code

(0, 0) 11
(0, 1) 22
(1, 0) 33
(1, 1) 43

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts