NumPy MCQ : Set 6

Python NumPy MCQ

1). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])
print("Number of non-zero elements: ", np.count_nonzero(x))
				
			

a) 4
b) 5
c) 6
d) 7

Correct answer is: a) 4
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[4, 8, 0], [2, 0, 6]]. The `np.count_nonzero()` function is then used to count the number of non-zero elements in the array `x`.

2). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3],
              [7, 4]])
print("Median of array:", np.median(x))
				
			

a) 3
b) 4
c) 5
d) 6

Correct answer is: b) 4.5
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median of all elements in the array `x`.

3). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3], [7, 4]])
print("Median of array along row:", np.median(x, axis=0))
				
			

a) [5, 3]
b) [7, 4]
c) [6, 3.5]
d) [4, 5]

Correct answer is: c) [6, 3.5]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median of the array along the rows, which means the median is computed for each column.

4). What is the output of the following code?

				
					import numpy as np
x = np.array([[5, 3], [7, 4]])
print("Median of array along column:", np.median(x, axis=1))
				
			

a) [4.0, 3.5]
b) [3.5, 4.0]
c) [3.0, 5.5]
d) [5.5, 3.0]

Correct answer is: a) [4.0, 5.5]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[5, 3], [7, 4]]. The `np.median()` function is then used to calculate the median along the column (axis 1) of the array `x`.

5). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])

for ele in np.nditer(x):
    print(ele, end=' ')
				
			

a) It prints the elements of the 2-dimensional NumPy array `x`.
b) It calculates the sum of all elements in the 2-dimensional NumPy array `x`.
c) It reshapes the 2-dimensional NumPy array `x` to a 1-dimensional array.
d) It creates a new 2-dimensional array with the same elements as `x`.

Correct answer is: a) It prints the elements of the 2-dimensional NumPy array `x`.
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[4, 8, 0], [2, 0, 6]]. It then uses a loop to iterate through the elements of the array `x` using the `np.nditer()` function. The `np.nditer()` function in NumPy allows iterating over all elements of an array regardless of its shape and dimensions. In the code, each element of the array `x` is printed using the loop with `print(ele, end=’ ‘)`.

6). What is the purpose of the following code?

				
					import numpy as np
x = np.array([2, 6, 3, 1])
print("Square of every element in the array: ", np.square(x))

				
			

a) It calculates the sum of all elements in the array `x`.
b) It calculates the mean of all elements in the array `x`.
c) It calculates the product of all elements in the array `x`.
d) It calculates the square of each element in the array `x`.

Correct answer is: d) It calculates the square of each element in the array `x`.
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [2, 6, 3, 1]. The `np.square()` function is then used to calculate the square of each element in the array `x`.

7). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, 0], [2, 0, 6]])
y = np.array([[5], [7]])

print(np.append(x, y, axis=1))
				
			

a) [[4, 8, 0], [2, 0, 6], [5], [7]]
b) [[4, 8, 0, 5], [2, 0, 6, 7]]
c) [[4, 5], [8, 7], [0, 0], [2, 6]]
d) [[4, 8, 0], [2, 0, 6], [5, 7]]

Correct answer is: b) [[4, 8, 0, 5], [2, 0, 6, 7]]
Explanation: The given code imports the NumPy library and creates two NumPy arrays `x` and `y`. The array `x` is a 2-dimensional array with the elements [[4, 8, 0], [2, 0, 6]]. The array `y` is a 2-dimensional array with the elements [[5], [7]]. The `np.append()` function is then used to append the array `y` to the array `x` along axis 1 (columns).

8). What is the output of the following code?

				
					import numpy as np
x = np.array([[4, 8, np.nan], [2, 4, 6]])
print("Old: \n", x)

print("New: \n", x[~np.isnan(x).any(axis=1)])
				
			

a) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[2. 4. 6.]]

b) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[4. 8. nan]]

c) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[4. 8. 6.]]

d) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[ 4. 8. nan]
[ 2. 4. 6.]]

Correct answer is: a) Old:
[[ 4. 8. nan]
[ 2. 4. 6.]]
New:
[[2. 4. 6.]]
Explanation: The given code uses NumPy to perform operations on a 2-dimensional array `x`, which contains some NaN (Not a Number) values. Let’s break down the code step by step. The code uses `np.isnan(x)` to create a boolean array, where `True` indicates the positions with NaN values in the original array. The `any(axis=1)` checks if there is any `True` in each row of the boolean array. The `~` is the logical NOT operator, which negates the boolean array. The modified array contains only the rows that do not have any NaN values. In this case, the row `[4, 8, nan]` is removed from the array, leaving only the row `[2, 4, 6]`.

9). What is the output of the following code?

				
					import numpy as np
x = np.array([3, 5, 1])
print("Magnitude of the given vector: ", np.linalg.norm(x))

				
			

a) 9
b) 3
c) 5.916079783099616
d) 35

Correct answer is: c) 5.916079783099616
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [3, 5, 1]. The `np.linalg.norm()` function is then used to calculate the magnitude (Euclidean norm) of the vector `x`. The magnitude of a vector is calculated as the square root of the sum of the squares of its elements.

10). What is the output of the following code?

				
					import numpy as np
x = np.array([8, 6, 7, 0, 7, 8, 6, 6])

unique, count = np.unique(x, return_counts=True)
print("Frequency of unique values in the given array:")
print(np.asarray((unique, count)))
				
			

a) [6, 7, 8, 0] [3, 2, 2, 1]
b) [0, 6, 7, 8] [1, 3, 2, 2]
c) [0, 6, 7, 8] [2, 3, 2, 1]
d) [0, 6, 7, 8] [3, 2, 1, 2]

Correct answer is: b) [0, 6, 7, 8] [1, 3, 2, 2]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [8, 6, 7, 0, 7, 8, 6, 6]. The `np.unique()` function is then used with the parameter `return_counts=True` to find the unique values and their corresponding frequencies in the array `x`.

11). What is the output of the following code?

				
					import numpy as np
x = np.array([4, 8, 0])

if x.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")

				
			

a) Array is empty
b) Array is not empty
c) 4 8 0
d) 3

Correct answer is: b) Array is not empty
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [4, 8, 0]. The code then checks the size of the array using the `x.size` attribute. Since `x` contains three elements, its size is not equal to zero. Therefore, the condition `x.size == 0` evaluates to False. As a result, the code enters the `else` block and prints “Array is not empty”.

12). What is the output of the following code?

				
					import numpy as np
x = np.array([3, 5, 1])
print("Product of the elements in the given array: ", x.prod())

				
			

a) 3
b) 15
c) 8
d) 11

Correct answer is: b) 15
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `x` with the elements [3, 5, 1]. The `x.prod()` function is then used to calculate the product of all elements in the array `x`.

13). What is the purpose of the following code?

				
					import pandas as pd
import numpy as np
 
x = np.arange(1, 16).reshape(3, 5)
 
DF = pd.DataFrame(x)
DF.to_csv("data1.csv")

df = pd.read_csv("data1.csv")
print(df)
				
			

a) It generates a NumPy array with numbers from 1 to 15 and reshapes it to a 3×5 matrix, then saves it as a CSV file.
b) It reads a CSV file named “data1.csv” and prints its content as a Pandas DataFrame.
c) It generates a Pandas DataFrame from a CSV file named “data1.csv” and prints its content.
d) It converts a NumPy array to a Pandas DataFrame and saves it as a CSV file named “data1.csv”.

Correct answer is: a) It generates a NumPy array with numbers from 1 to 15 and reshapes it to a 3×5 matrix, then saves it as a CSV file.
Explanation: `import pandas as pd`: Imports the Pandas library with the alias `pd`. `import numpy as np`: Imports the NumPy library with the alias `np`. `x = np.arange(1, 16).reshape(3, 5)`: Generates a NumPy array with numbers from 1 to 15 using `np.arange()` and reshapes it to a 3×5 matrix using `reshape()` method. `DF = pd.DataFrame(x)`: Creates a Pandas DataFrame `DF` from the NumPy array `x`. `DF.to_csv(“data1.csv”)`: Saves the Pandas DataFrame `DF` as a CSV file named “data1.csv”. `df = pd.read_csv(“data1.csv”)`: Reads the CSV file “data1.csv” and creates a new Pandas DataFrame `df`. `print(df)`: Prints the content of the Pandas DataFrame `df`.

14). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])

for i in range(0, 2):
    print(f"{i+1} column: ", x[:, i])
				
			

a) It prints the sum of elements in each row of the array `x`.
b) It prints the transpose of the array `x`.
c) It prints the first two columns of the array `x`.
d) It prints the elements of the second row in reverse order.

Correct answer is: c) It prints the first two columns of the array `x`.
Explanation: The given code imports the NumPy library and creates a 3×3 2-dimensional NumPy array `x` with the elements. The code then uses a for loop to iterate over the columns of `x` with the range from 0 to 2 (excluding 2). For each iteration, it prints the respective column of the array `x` using the slicing syntax `x[:, i]`, where `i` is the column index.

15). What is the purpose of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])
print(x[0:2, 0:2])
				
			

a) Prints the first two elements of each row.
b) Prints the first two rows and first two columns of the array.
c) Prints the first two rows and first three columns of the array.
d) Prints the first two elements of each column.

Correct answer is: b) Prints the first two rows and first two columns of the array.
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements: The code then uses slicing to extract a sub-array from `x` using the notation `x[0:2, 0:2]`.
Slicing notation `x[0:2, 0:2]` means the following:
– `0:2` selects the first and second rows (index 0 and 1) of the array.
– `0:2` selects the first and second columns (index 0 and 1) of the array.

16). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])
print("Sum of all columns: ", x.sum(axis=0))

				
			

a) [23, 22, 10]
b) [6, 5, 7, 10, 9, 1, 7, 8, 2]
c) [17, 22, 10]
d) [23, 9, 17]

Correct answer is: a) [23, 22, 10]
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements: The `x.sum(axis=0)` calculates the sum of all columns (along axis 0) in the array `x`.
The sum of each column is calculated as follows:
Column 1 sum: 6 + 10 + 7 = 23
Column 2 sum: 5 + 9 + 8 = 22
Column 3 sum: 7 + 1 + 2 = 10

17). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, np.nan], [np.nan, 9, 1], [7, 8, 2]])

temp = np.ma.masked_array(x, np.isnan(x))
print("Array after removing nan values: \n", temp)

				
			

a)
[[6.0 5.0 –]
[– 9.0 1.0]
[7.0 8.0 2.0]]

b)
[[6.0 5.0 0.0]
[0.0 9.0 1.0]
[7.0 8.0 2.0]]

c)
[[6.0 5.0 0.0]
[0.0 9.0 1.0]
[7.0 8.0 2.0]]

d)
[[6.0 5.0 1.0]
[1.0 9.0 1.0]
[7.0 8.0 2.0]]

Correct answer is: a)
[[6.0 5.0 –]
[– 9.0 1.0]
[7.0 8.0 2.0]]
Explanation: The given code creates a 2-dimensional NumPy array `x` with the elements [[6, 5, np.nan], [np.nan, 9, 1], [7, 8, 2]]. The `np.isnan()` function is used to identify the NaN (Not a Number) values in the array `x`. The `np.ma.masked_array()` function then creates a masked array where the NaN values are masked or hidden. The masked array `temp` will have the NaN values replaced with ‘–‘, representing that these values are masked and not considered in computations.

18). What is the output of the following code?

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

output = np.concatenate((x, y))
print("\nAfter concatenate:")
print(output)
				
			

a) [1, 2, 3, 4, 5, 6]
b) [[1, 2, 3], [4, 5, 6]]
c) [[1, 2, 3, 4, 5, 6]]
d) [5, 7, 9]

Correct answer is: a) [1, 2, 3, 4, 5, 6]
Explanation: The given code imports the NumPy library and creates two 1-dimensional NumPy arrays, `x` and `y`. The `np.concatenate()` function is then used to concatenate these two arrays. The `np.concatenate()` function concatenates arrays along a specified axis. If the axis is not specified, it defaults to 0, which means the arrays will be concatenated along the first dimension.

19). What is the purpose of the following code?

				
					import numpy as np
import pandas as pd
x = np.random.rand(6, 3)

df = pd.DataFrame(x, columns=['A', 'B', 'C'])
print("\nPandas DataFrame: ")
print(df)
				
			

a) It generates a NumPy array of random floating-point numbers with a shape of (6, 3).
b) It generates a Pandas DataFrame with 6 rows and 3 columns containing random floating-point numbers.
c) It calculates the mean of a Pandas DataFrame and prints the result.
d) It creates a Pandas DataFrame from a given NumPy array and prints the DataFrame.

Correct answer is: b) It generates a Pandas DataFrame with 6 rows and 3 columns containing random floating-point numbers.
Explanation:
1. The code imports the NumPy library as `np` and the Pandas library as `pd`.
2. The `np.random.rand(6, 3)` function generates a NumPy array of random floating-point numbers with a shape of (6, 3).
3. The `pd.DataFrame()` function takes the NumPy array `x` and converts it into a Pandas DataFrame with 6 rows and 3 columns. The columns are labeled as ‘A’, ‘B’, and ‘C’ respectively, as specified by the `columns` parameter.
4. The `print(df)` statement displays the Pandas DataFrame, showing the 6 rows and 3 columns of random floating-point numbers.

20). What is the output of the following code?

				
					import numpy as np
x = np.arange(15).reshape(3, 5)
y = np.arange(20).reshape(4, 5)

if x.shape == y.shape:
    print("Same dimensions")
else:
    print("Different dimensions")
				
			

a) Same dimensions
b) Different dimensions

Correct answer is: b) Different dimensions
Explanation: The given code imports the NumPy library and creates two NumPy arrays, `x` and `y`. The array `x` is created using `np.arange(15)` and reshaped into a 3×5 array, while the array `y` is created using `np.arange(20)` and reshaped into a 4×5 array. Next, the code checks whether the shapes of arrays `x` and `y` are equal using the `x.shape == y.shape` condition. If the shapes are equal, it prints “Same dimensions”, and if the shapes are different, it prints “Different dimensions”.

21). What is the output of the following code?

				
					import numpy as np
x = np.array([[6, 5, 7], [10, 9, 1], [7, 8, 2]])

print((~x.any(axis=0)).any())
				
			

a) True
b) False

Correct answer is: b) False
Explanation: The given code imports the NumPy library and creates a 2-dimensional NumPy array `x` with the elements [[6, 5, 7], [10, 9, 1], [7, 8, 2]]. The expression `(~x.any(axis=0))` is used to find the columns in the array `x` that contain at least one nonzero element. The `x.any(axis=0)` returns a boolean array indicating for each column whether it contains at least one nonzero element.

22). What is the output of the following code?

				
					import numpy as np
angle = np.array([45, 13])
print(f"Sin of {angle}: ", np.sin(angle))
				
			

a) [0.85090352, 0.42016704]
b) [0.52532199, 0.96355819]
c) [0.01745241, 0.85607777]
d) [0.57357644, 0.14112001]

Correct answer is: a) [0.85090352, 0.42016704]
Explanation: The given code imports the NumPy library and creates a NumPy array `angle` with the elements [45, 13]. The `np.sin()` function is then used to calculate the sine of the angles in the `angle` array. The sine of an angle in degrees can be calculated using the NumPy `sin()` function, which takes an array of angles in radians as input. To convert degrees to radians, we need to multiply the angle by π/180.

23). What is the purpose of the following code?

				
					import numpy as np
age = np.array([20, 25, 21, 23, 26, 27, 26, 30, 24, 26])

print("Standard Deviation: ", np.std(age))
				
			

a) It calculates the mean age of the given data.
b) It calculates the variance of the ages in the dataset.
c) It calculates the standard deviation of the ages in the dataset.
d) It calculates the total number of elements in the array.

Correct answer is: c) It calculates the standard deviation of the ages in the dataset.
Explanation: The given code imports the NumPy library and creates a NumPy array `age` containing the ages of a group of individuals. The `np.std()` function is then used to calculate the standard deviation of the ages in the dataset. The standard deviation is a measure of how spread out the values are from the mean. It is calculated using the formula:
Standard Deviation = sqrt((Σ (x – mean)^2) / N)
where:
– `x` represents each individual value (age) in the dataset.
– `mean` is the mean (average) of the ages.
– `N` is the total number of elements (ages) in the dataset.

24). What is the purpose of the following code?

				
					import numpy as np
arr = np.array([12.202, 90.23120, 123.88, 23.202])  
print(np.round(arr, 2))
				
			

a) It calculates the mean of the array elements.
b) It calculates the standard deviation of the array elements.
c) It rounds the array elements to the nearest integer.
d) It rounds the array elements to two decimal places.

Correct answer is: d) It rounds the array elements to two decimal places.
Explanation: The given code imports the NumPy library and creates a NumPy array `arr` with the elements [12.202, 90.23120, 123.88, 23.202]. The `np.round()` function is then used to round the elements of the array `arr` to two decimal places. The rounded array elements are as follows:
Rounded array = [12.20, 90.23, 123.88, 23.20]

25). What is the output of the following code?

				
					import numpy as np
arr = np.array([12.202, 90.23120, 123.88, 23.202])

print(np.floor(arr))
				
			

a) [12, 90, 123, 23]
b) [12.0, 90.0, 123.0, 23.0]
c) [13, 91, 124, 24]
d) [12.202, 90.231, 123.88, 23.202]

Correct answer is: a) [12, 90, 123, 23]
Explanation: The given code imports the NumPy library and creates a 1-dimensional NumPy array `arr` with the elements [12.202, 90.23120, 123.88, 23.202]. The `np.floor()` function is then used to round down each element in the array `arr` to the nearest integer.

Leave a Comment