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 do you convert Pandas DataFrame to a NumPy array?

Answer»

The to_numpy() method of the NumPy package can be used to convert Pandas DataFrame, Index and Series objects.

Consider we have a DataFrame df, we can either convert the whole Pandas DataFrame df to NumPy array or even select a subset of Pandas DataFrame to NumPy array by using the to_numpy() method as shown in the example below:

import pandas as pd
import numpy as np
# Pandas DataFrame
df = pd.DataFrame(data={'A': [3, 2, 1], 'B': [6,5,4], 'C': [9, 8, 7]},
index=['i', 'j', 'k'])
print("Pandas DataFrame: ")
print(df)

# Convert Pandas DataFrame to NumPy Array
np_arr = df.to_numpy()
print("Pandas DataFrame to NumPy array: ")
print(np_arr)


# Convert specific columns of Pandas DataFrame to NumPy array
arr = df[['B', 'C']].to_numpy()
print("Convert B and C columns of Pandas DataFrame to NumPy Array: ")
print (arr)

The output of the above code is

Pandas DataFrame:
A B C
i 3 6 9
j 2 5 8
k 1 4 7
Pandas DataFrame to NumPy array:
[[3 6 9]
[2 5 8]
[1 4 7]]
Convert B and C columns of Pandas DataFrame to NumPy Array:
[[6 9]
[5 8]
[4 7]]
2.

How do you concatenate 2 NumPy arrays?

Answer»

Concatenating 2 arrays by adding elements to the end can be achieved by making use of the concatenate() method of the NumPy package. Syntax:

np.concatenate((a1, a2, ...), axis=0, out=None)

where,


  • a1,a2: arrays of the same shape

  • axis: Represents the axis along which the arrays are joined. The default value is 0.

  • out: If mentioned, it specifies the destination for placing the result.

For example:

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

# Concatenate with axis 0
c = np.concatenate((a,b), axis=0)
print("With axis 0: \n",c )

# Concatenate with axis 1 (b.T represents transpose matrix)
d = np.concatenate((a,b.T), axis=1)
print("With axis 1: \n",d )

The output would be:

With axis 0:
[[1 2]
[3 4]
[5 6]]
With axis 1:
[[1 2 5]
[3 4 6]]

Notice how the arrays are concatenated with different values of the axis.


3.

How do you multiply 2 NumPy array matrices?

Answer»

We can make use of the dot() for multiplying matrices represented as NumPy arrays. This is represented in the code snippet below:

import numpy as np

# NumPy matrices
A = np.arange(15,24).reshape(3,3)
B = np.arange(20,29).reshape(3,3)
print("A: ",A)
print("B: ",B)

# Multiply A and B
result = A.dot(B)
print("Result: ", result)

Output

A: [[15 16 17]
[18 19 20]
[21 22 23]]
B: [[20 21 22]
[23 24 25]
[26 27 28]]
Result: [[1110 1158 1206]
[1317 1374 1431]
[1524 1590 1656]]
4.

How is arr[:,0] different from arr[:,[0]]

Answer»

arr[:,0] - Returns 0th index elements of all rows. In other words, return the first column elements.

 import numpy as np

arr = np.array([[1,2,3,4],[5,6,7,8]])
new_arr =arr[:,0]
print(new_arr)

Output:

 [1 5]

arr[:,[0]] - This returns the elements of the first column by adding extra dimension to it.

import numpy as np

arr = np.array([[1,2,3,4],[5,6,7,8]])
new_arr =arr[:,[0]]
print(new_arr)

Output:

[[1]
[5]]
5.

How do we check for an empty array (or zero elements array)?

Answer»

We can check for the emptiness of a NumPy array by making use of the size attribute.
Let us consider the below example. We have NumPy array arr filled with zeros. If the size element returns zero, that means the array is empty or it only consists of zeros.

import numpy as np
arr = np.zeros((1,0)) #returns empty array
print(arr.size) #returns 0

This return 0


6.

How do you count the frequency of a given positive value appearing in the NumPy array?

Answer»

We can make use of the bincount() function to compute the number of times a given value is there in the array. This function accepts only positive integers and boolean expressions as the arguments.

import numpy as np
arr = np.array([1, 2, 1, 3, 5, 0, 0, 0, 2, 3])
result = np.bincount(arr)
print(result)

The result is:

[3 2 2 2 0 1]

It has to be noted here that each element represents the count of the corresponding index value present in the original array. This is demonstrated in the below image:


7.

How is np.mean() different from np.average() in NumPy?

Answer»

  • np.mean() method calculates the arithmetic mean and provides additional options for input and results. For example, it has the option to specify what data types have to be taken, where the result has to be placed etc.

  • np.average() computes the weighted average if the weights parameter is specified. In the case of weighted average, instead of considering that each data point is contributing equally to the final average, it considers that some data points have more weightage than the others (unequal contribution).


8.

How can you reverse a NumPy array?

Answer»

There are two ways of reversing a NumPy array.


  • Method 1: Using the slicing method: We can make use of [::-1] for reversing the array. The following example demonstrates this:
import numpy as np

# create numpy array
arr = np.array([1, 2, 4, 6])

# To reverse array
reverse_arr = arr[::-1]
print(reverse_arr)

Output:

[6 4 2 1]

  • Method 2: flipud function: This function is provided by NumPy to reverse the NumPy array. Let us see the below example about its usage.
import numpy as np

# create numpy array
arr = np.array([1, 2, 4, 5, 6])

#flipud method for reversing
reverse_arr = np.flipud(arr)
print(reverse_arr)

Output:

[6 5 4 2 1]
9.

How do you find the data type of the elements stored in the NumPy arrays?

Answer»

NumPy supports the following datatypes:


  • i - integer

  • S - string

  • b - boolean

  • f - float

  • u - unsigned integer

  • c - complex float

  • m - timedelta

  • M - datetime

  • O - object

  • U - unicode string

  • V - fixed memory chunk for types such as void
    We can make use of the dtype property that returns the type of the elements stored in the NumPy array. Let us consider the below code snippet. We create some sample arrays and we see what the data types of these arrays are.

import numpy as np

arr1 = np.array([1, 2, 3, 4])
arr2 = np.array(['I', 'love', 'Interviewbit']) # Stored as Unicode characters with length of characters ranging from 1 to 12
arr3 = np.array([1, 2, 3, 4], dtype='S') # Creating numpy array of defined type string

print(arr1.dtype)
print(arr2.dtype)
print(arr3.dtype)

The output will be:

int64
<U12
|S1
10.

What are ways of creating 1D, 2D and 3D arrays in NumPy?

Answer»

Consider you have a normal python list. From this, we can create NumPy arrays by making use of the array function as follows:

  • One-Dimensional array
 import numpy as np
 
arr = [1,2,3,4] #python list
numpy_arr = np.array(arr) #numpy array
  • Two-Dimensional array
 import numpy as np

arr = [[1,2,3,4],[4,5,6,7]]
numpy_arr = np.array(arr)
  • Three-Dimensional array
 import numpy as np

arr = [[[1,2,3,4],[4,5,6,7],[7,8,9,10]]]
numpy_arr = np.array(arr)

Using the np.array() function, we can create NumPy arrays of any dimensions.


11.

What are ndarrays in NumPy?

Answer»

ndarray object is the core of the NumPy package. It consists of n-dimensional arrays storing elements of the same data types and also has many operations that are done in compiled code for optimised performance. These arrays have fixed sizes defined at the time of creation. Following are some of the properties of ndarrays:


  • When the size of ndarrays is changed, it results in a new array and the original array is deleted.

  • The ndarrays are bound to store homogeneous data.

  • They provide functions to perform advanced mathematical operations in an efficient manner.


12.

How are NumPy arrays better than Python’s lists?

Answer»

  • Python lists support storing heterogeneous data types whereas NumPy arrays can store datatypes of one nature itself. NumPy provides extra functional capabilities that make operating on its arrays easier which makes NumPy array advantageous in comparison to Python lists as those functions cannot be operated on heterogeneous data.

  • NumPy arrays are treated as objects which results in minimal memory usage. Since Python keeps track of objects by creating or deleting them based on the requirements, NumPy objects are also treated the same way. This results in lesser memory wastage.

  • NumPy arrays support multi-dimensional arrays.

  • NumPy provides various powerful and efficient functions for complex computations on the arrays.

  • NumPy also provides various range of functions for BitWise Operations, String Operations, Linear Algebraic operations, Arithmetic operations etc. These are not provided on Python’s default lists.


13.

Why is NumPy preferred over Matlab, Octave, Idl or Yorick?

Answer»

NumPy is an open-source, high-performing library that allows complex mathematical and scientific computational capabilities. It makes use of Python language which is a high-level, easy-to-learn, general-purpose programming language. It supports the following:


  • Powerful functions for performing complex mathematical operations on multi-dimensional matrices and arrays. The operations on ndarrays of NumPy are approximately up to 50% faster when compared to operations on native lists using loops. This efficiency is very much useful when the arrays have millions of elements.

  • Provides indexing syntax to access portions of data easily in a large array.

  • Provides built-in functions which help to easily perform operations related to linear algebra and statistics.

  • It takes only a few lines of code to achieve complex computations using NumPy.


14.

What is NumPy? Why should we use it?

Answer»

NumPy (also called Numerical Python) is a highly flexible, optimized, open-source package meant for array processing. It provides tools for delivering high-end performance while dealing with N-dimensional powerful array objects. It is also beneficial for performing scientific computations, mathematical, and logical operations, sorting operations, I/O functions, basic statistical and linear algebra-based operations along with random simulation and broadcasting functionalities. Due to the vast range of capabilities, NumPy has become very popular and is the most preferred package. The following image represents the uses of NumPy.


Previous Next