Explore topic-wise InterviewSolutions in Current Affairs.

This section includes 7 InterviewSolutions, each offering curated multiple-choice questions to sharpen your Current Affairs knowledge and support exam preparation. Choose a topic below to get started.

1.

How is fliplr different from flipud methods in NumPy?

Answer»

The fliplr() method is used for flipping an array in the left or right direction. The columns are preserved but the order of elements in the columns would be different than before. This has been represented in the image below:

We see that the positions of the elements are flipped left or right than their original position in the result.

Syntax of fliplr:

np.fliplr(arr)

where arr is the array that has to be flipped.

The flipud function also flips the array but in the up or down direction. The rows are preserved in this case but they can appear in a different order in the result. This is represented in the image below:

Here, we see that the numbers 1, 3 and 5 elements are flipped in the up/down direction in the result.

The syntax for flipud:

np.flipud(arr)

where arr is the array that has to be flipped.


2.

How will you implement the moving average for the 1D array in NumPy?

Answer»

We can make use of the convolve() method. Here, it leverages the way discrete convolution is computed and uses it to find the rolling mean (moving average). Here, the sequence of ones of length equal to the length of the sliding window is convolved with the array.

We first define a calculate_moving_average function which performs the convolution of an array with the sequence of ones of sliding window length w. The mode of the convolve method will be ‘valid’ to generate the points only where the overlapping of the sequence is complete.

import numpy as np
def calculate_moving_average(arr, w):
return np.convolve(arr, np.ones(w),'valid')/w

The above-defined function can be then used for finding the moving average as shown in the examples below:

arr1 = np.array([4,5,8,9,3,2,4,2,0,2])
print("Moving average of window length 2: ")
av1 = calculate_moving_average(arr1, 2)
print(av1)

print("Moving average of window length 4: ")
av2 = calculate_moving_average(arr1, 4)
print(av2)

Output:

Moving average of window length 2:
[4.5 6.5 8.5 6. 2.5 3. 3. 1. 1. ]
Moving average of window length 4:
[6.5 6.25 5.5 4.5 2.75 2. 2. ]
3.

What happens when we use the arrays_split() method for splitting the NumPy array?

Answer»

The array_split() method is similar to the split() method as it helps in splitting a given array to multiple subarrays. The main difference is that the array_split() allows sections to be an integer which does not result in equal array division. For an array of length L, if we want it to split to N subarrays, then L % N subarrays of size (L//N + 1) and remaining subarrays are of size L//N.

In the above figure, we see there are 5 elements in the array, we want to split the array to 3 subarrays. So L % N = 5%3 = 2 subarrays of size (L//N +1) = (5//3 +1) = 2 are returned and remaining 1 subarray of size L//N = 1 is returned.

Syntax:

np.array_split(array, sections, axis=0)

where,


  • array - Given Input array.

  • sections - List of indices or Number of subarrays to be returned.

  • axis - Axis along which values have to be appended.

The code for the example illustrated above is:

import numpy as np
arr = np.arange(5.0)
split_arrs = np.array_split(arr, 3)
split_arrs

Output:

[array([0., 1.]), array([2., 3.]), array([4.])]
4.

What happens when the split() method is used for splitting NumPy arrays?

Answer»

1. np.split() : Equally splits arrays into multiple sub-arrays. It raises Value Error when the split cannot be equal.

  • Syntax:
np.split(array, sections, axis=0)

where,


  • array - array that needs to be split

  • sections -
    • If we give an integer X, X equal sub-arrays are obtained after dividing the array. If the split is not possible, ValueError is raised.
      • For example:



 import numpy as np
a = np.arange(8)
split_arr = np.split(a, 2)
split_arr

Output

[array([0, 1, 2, 3]), array([4, 5, 6, 7])]
  • If we give a 1-D sorted array then the entries would represent where the array would be split along the axis. For instance if we provide [2:3] and axis as 0, then the result would be
    [arr[0:2], arr[2:3], arr[3:]]

    • If the provided index exceeds the array dimension along the given axis, then an empty subarray will be returned.

    • For example:


[array([0., 1., 2.]),
array([3.]),
array([4.]),
array([5.]),
array([], dtype=float64),
array([], dtype=float64),
array([], dtype=float64)]

The output would be:

import numpy as np
a = np.arange(6.0)
split_arr = np.split(a, [3, 4, 5, 6, 7,8])
split_arr
  • axis - Along what axis the array has to be split. By default, the value is 0

5.

How is Vectorization related to Broadcasting in NumPy?

Answer»

Vectorization involves delegating NumPy operations internally to optimized C language functions to result in faster Python code. Whereas Broadcasting refers to the methods that allow NumPy to perform array-related arithmetic operations. The size or shape of the arrays does not matter in this case. Broadcasting solves the problem of mismatched shaped arrays by replicating the smaller array along the larger array to ensure both arrays are having compatible shapes for NumPy operations. Performing Broadcasting before Vectorization helps to vectorize operations which support arrays of different dimensions.


6.

How do you find the local peaks (or maxima) in a 1-D NumPy Array?

Answer»

Peaks are the points that are surrounded by smaller value points on either side as shown in the image below:

There are two ways of finding local maxima:

Using .where() method: This method lists all positions/indices where the element value at position i is greater than the element on either side of it. This method does not check for the points that have only one neighbour. This is demonstrated in the example below:

import numpy as np
# define NumPy array
arr = np.array([1, 4, 8, 1, 3, 5, 1, 6, 1, -5, -1, 19, 2])


maxima_peaks_positions = np.where((arr[1:-1] > arr[0:-2]) * (arr[1:-1] > arr[2:]))[0] + 1
print(maxima_peaks_positions)

Output:

[ 2 5 7 11]]

  • The +1 at the end of the expression is required as it finds the indexes within the slice arr[1:-1] and not the entire array arr.

  • The where() method returns a tuple of arrays where the first element is our required array. Hence we add [0] after the where method.

Using combination of .diff(), .sign() and .where() method:


  • In this method, we calculate the difference between each element using the diff() method of NumPy.

  • Then we use the sign() method on the array to get the sign of difference.

  • The value can be either -1 or +1. This result is then passed on to another diff() method which returns 0, -2 or +2 value. The value 0 indicates that the points are continuously increasing or decreasing, +2 indicates minimum peak and -2 indicates maximum peak (local maxima).

  • We then identify the position or indexes of the local maxima using the where() method. The reason for using +1 at the end of where and [0] after where is the same as the explanation described in Method 1 for finding local maxima.

The following code example demonstrates this:

import numpy as np
# define NumPy array
arr = np.array([1, 4, 8, 1, 3, 5, 1, 6, 1, -5, -1, 19, 2])

all_peaks = np.diff(np.sign(np.diff(arr)))
maxima_peaks_positions = np.where(all_peaks == -2)[0] + 1
print(maxima_peaks_positions)

Output:

[ 2 5 7 11]]
7.

How is vstack() different from hstack() in NumPy?

Answer»

Both methods are used for combining the NumPy arrays. The main difference is that the hstack method combines arrays horizontally whereas the vstack method combines arrays vertically.
For example, consider the below code.

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

# vstack arrays
c = np.vstack((a,b))
print("After vstack: \n",c)
# hstack arrays
d = np.hstack((a,b))
print("After hstack: \n",d)

The output of this code would be:

After vstack:
[[1 2 3]
[4 5 6]]
After hstack:
[1 2 3 4 5 6]

Notice how after the vstack method, the arrays were combined vertically along the column and how after the hstack method, the arrays were combined horizontally along the row.


8.

What do you understand by Vectorization in NumPy?

Answer»

Function Vectorization technically means that the function is applied to all elements in the array. Typically, certain python functionalities on arrays (such as loops) are slower in nature because python arrays can contain elements of different data types. Since the C program expects a specific datatype, there are chances of compiler optimisation which makes C code run faster. Since NumPy arrays support storing elements of a single datatype, most of the implementations of the functions written in NumPy meant for arithmetic, logical operations etc have optimised C program code under their hood. Additionally, NumPy also helps developers create their own vectorised functions by following the below steps:


  • Write your required function that takes array elements as parameters.

  • Vectorize the function by making use of the vectorize() method of the NumPy package.

  • Give array inputs to the vectorized function.

The below example demonstrates the process of vectorization.

import numpy as np
# Define your function
def add(arr1, arr2):
return (arr1 + arr2)

arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])

#vectorize add method
vectorized_add = np.vectorize(add)

#call vectorized method
result = vectorized_add(arr1, arr2)

print(result)

The output of above code

 [5 7 9]
Previous Next