0% found this document useful (0 votes)
2 views20 pages

NumPy Interview Questions With Answers - GeeksforGeeks

The document provides a comprehensive overview of NumPy, an open-source Python library for numerical computing, including common interview questions and answers. Key topics covered include array creation, mathematical operations, data types, and methods for handling and manipulating arrays. It also addresses advanced concepts such as matrix inversion, outlier detection, and handling missing values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

NumPy Interview Questions With Answers - GeeksforGeeks

The document provides a comprehensive overview of NumPy, an open-source Python library for numerical computing, including common interview questions and answers. Key topics covered include array creation, mathematical operations, data types, and methods for handling and manipulating arrays. It also addresses advanced concepts such as matrix inversion, outlier detection, and handling missing values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Courses

Search... Tutorials
Sign In
Practice
DSA Practice Problems C C++ Java Python JavaScript Data Science Machine Learning Courses
Jobs

NumPy Interview Questions with Answers


Last Updated : 20 Sep, 2025

NumPy is an open-source Python library used for numerical computing and handling
large multi-dimensional arrays efficiently. In interviews, questions on NumPy are often
asked to evaluate your understanding of array operations, mathematical functions and
performance optimization. Below are some of the most frequently asked interview
questions covering key NumPy topics.

1. What is NumPy and how to create a NumPy array?

NumPy is used for numerical and scientific computing. It offers support for arrays,
matrices and a variety of mathematical operations that can effectively operate on these
arrays.

We can create NumPy arrays using various methods. Here are some common ways to
create NumPy arrays:

1. Using np. array()


2. [Link]()
3. [Link]()
4. [Link]()
5. [Link]()
6. [Link]()

2. What are the main features of Numpy?

Here are some main features of the NumPy:

1. Fast and Efficient


2. Mathematical Functions
3. Broadcasting
4. Integration with other libraries
5. Multi-dimensional arrays
6. Indexing and Slicing
7. Memory Management

3. How do you calculate the dot product of two NumPy arrays?


Calculating the dot product of two NumPy arrays we used [Link]() function and we
also used the @ operator:
1. Using [Link]() function:

[Link](a, b)

a: The first input array (NumPy array).


b: The second input array (NumPy array).
2. Using the @ operator

a @ b

Both methods will return the dot product of the two arrays as a scalar value.

4. What is the difference between a shallow copy and a deep copy in NumPy?

In numPy we have two ways to copy an array. shallow copy and deep copy are two most
used methods used in numpy to copy an array. Here is the main difference between both
of them.

Feature Shallow Copy Deep Copy

Definition A new array that is a view of the A completely new and independent
original array's data. array with its own copy of the data.

Memory References the same memory Allocates new memory, duplicating


location as the original array. the data.

Duplication No actual duplication of data; only


Full duplication of data is created.
references.

Effect of Changes in the original array reflect Changes in the original array do not
Changes in the shallow copy and vice versa. affect the deep copy and vice versa.

5. How do you reshape a NumPy array?

We can reshape a NumPy array by using the reshape() method or the [Link]()
function. it help us to change the dimensions of the array and keep all the elements
constant.
1. Using the reshape() method:

array1= original_array.reshape(new_shape)

2. Using the [Link]() function:

array1 = [Link](original_array, new_shape)


In both cases, original_array is the existing NumPy array you want to reshape and
new_shape is a tuple specifying the desired shape of the new array.

6. How to perform element-wise operations on NumPy arrays?

To perform element-wise operations on NumPy arrays, you can use standard arithmetic
operators. NumPy automatically applies these operations element-wise when you use
them with arrays of the same shape.

import numpy as np

# Create two NumPy arrays


array1 = [Link]([1, 2, 3, 4, 5])
array2 = [Link]([6, 7, 8, 9, 10])

# Perform element-wise operations


result_addition = array1 + array2
result_subtract = array1 - array2
result_multiply = array1 * array2
result_divide = array1 / array2
result_power = [Link](array1, 2)

# Print results
print("Addition:", result_addition)
print("Subtraction:", result_subtract)
print("Multiplication:", result_multiply)
print("Division:", result_divide)
print("Power:", result_power)

Output:

Addition: [ 7 9 11 13 15]
Subtraction: [-5 -5 -5 -5 -5]
Multiplication: [ 6 14 24 36 50]
Division: [0.16666667 0.28571429 0.375 0.44444444 0.5 ]
Power: [ 1 4 9 16 25]

7. How to generate random numbers with NumPy?

NumPy provides a wide range of functions for generating random numbers. You can
generate random numbers from various probability distributions, set seeds for
reproducibility and more. Here are some common ways to generate random numbers
with NumPy:
1. Using [Link]()
Generating a Random Float between 0 and 1 using [Link]()

random_float = [Link]()

2. Using [Link]()
Generating a Random Integer within a Range using [Link]().

random_integer = [Link]()

3. Using [Link]()

random_float = [Link]()

4. Using [Link]()
We can set a seed using [Link]() to ensure that the generated random numbers
are reproducible.

[Link](seed_value)

8. How can you create a NumPy array from a Python list?

We can create a NumPy array from a Python list using the [Link]() constructor provided
by NumPy.

python_list = [1, 2, 3, 4, 5]

numpy_array = [Link](python_list)

9. How can you access elements in a NumPy array based on specific conditions?

We can access elements in a NumPy array based on specific conditions using boolean
indexing. Boolean indexing allows us to create true and false values based on a
condition.

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])

condition = arr > 3

selected_elements = arr[condition]
print("Selected Elements (greater than 3):", selected_elements)

Output:

Selected Elements (greater than 3): [4 5]

10. What are some common data types supported by NumPy?

In NumPy there are so many data types that are used to specify the type of data which
stored in array. This data type provide control that how data stored in memory during
operations. Some common data types supported by NumPy include:
1. int
2. float
3. complex
4. bool
5. object
6. datetime

11. How can you concatenate two NumPy arrays vertically?

We can concatenate two NumPy arrays vertically (along the rows) using the [Link]()
function or the [Link]() function with the axis parameter set to 0. Here's how to
do it with both methods:
1. Using [Link]()

array= [Link]((array1, array2))

2. Using [Link]() with axis

array= [Link]((array1, array2), axis=0)

12. What is Matrix Inversion in NumPy?

Matrix inversion in NumPy refers to the process of finding the inverse of a square matrix.
The identity matrix is produced when multiplying the original matrix by the inverse of the
matrix. In other words, if A is a square matrix and A^(-1) is its inverse, then A * A^(-1) =
I, where I is the identity matrix.

NumPy provides a convenient function called [Link]() to compute the inverse of


a square matrix. Here's how you can use it:

import numpy as np

# Define a square matrix


A = [Link]([[1, 2, 3],
[0, 1, 4],
[5, 6, 0]])

# Calculate the inverse of the matrix


A_inverse = [Link](A)

# Print results
print("Original Matrix:\n", A)
print("Inverse Matrix:\n", A_inverse)

Output:

Original Matrix:
[[ 1 2 3]
[ 0 1 4]
[ 5 6 0]]
Inverse Matrix:
[[-24. 18. 5.]
[ 20. -15. -4.]
[ -5. 4. 1.]]

13. Define the var and mean function in NumPy.

In NumPy, the var function is used to compute the variance of elements in an array or
along a specified axis. Variance is a measure of the spread or dispersion of data points.

[Link](a, axis=None, dtype=None)

a: The input array for which you want to calculate the variance.
axis: Axis or axes along which the variance is computed. If not specified, the variance is
calculated for the whole array. It can be an integer or a tuple of integers to specify
multiple axes.
dtype: The data type for the returned variance. If not specified, the data type is
inferred from the input array.

The arithmetic mean (average) in NumPy can be calculated using [Link](). This
method tallies elements in an array, whether it be along a specified axis or the whole
array, if no axis is explicitly mentioned. The summation of all elements is then divided by
the overall number of elements which provides the average.

[Link](a, axis=None)

a: The input array for which you want to calculate the mean.
axis : The axis or axes along which the mean is computed. If not specified, the mean is
calculated over the entire array.

14. Convert a multidimensional array to 1D array.

You can convert a multidimensional array to a 1D array which is also known as flattening
the array in NumPy using various methods. Two common methods are using for the
Convert a multidimensional array to 1D array.
1. Using flatten():

# Create a multidimensional array


multidimensional_array = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Use the flatten() method to convert it to a 1D array


one_dimensional_array = multidimensional_array.flatten()

print("one dimensional array", one_dimensional_array)


Output:

one dimensional array [1 2 3 4 5 6 7 8 9]

2. Using ravel():

# Create a multidimensional array


multidimensional_array = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Use the ravel() method to convert it to a 1D array


one_dimensional_array = multidimensional_array.ravel()

print("one dimensional array", one_dimensional_array)

Output:

one dimensional array [1 2 3 4 5 6 7 8 9]

Both of these methods will flatten the multidimensional array into a 1D array. The
primary difference between them:

Flatten() returns a new copy of the array. Any modifications in the flattened array do
not affect the original array
Ravel() returns a flattened view of the original array whenever possible. Changes
made to the raveled array may affect the original array since they share the same data
in memory.

15. How can you identify outliers in a NumPy array?

Identifying and removing outliers in a NumPy array involves several steps. Outliers are
data points that significantly deviate from the majority of the data and can adversely
affect the results of data analysis. Here's a general approach to identify and remove
outliers:
Identifying Outliers:
1. Calculate Descriptive Statistics: Compute basic statistics like the mean and standard
deviation of the array to understand the central tendency and spread of the data.

import numpy as np

# Sample data
arr = [Link]([10, 12, 12, 13, 12, 11, 300, 14, 13, 12])

# Calculate mean and standard deviation


mean = [Link](arr)
std = [Link](arr)

# Define threshold (e.g., 2 standard deviations from mean)


threshold = 2
outliers = arr[[Link](arr - mean) > threshold * std]

print("Outliers:", outliers)

Output:

Outliers: [300]

2. Using IQR: IQR (Interquartile Range) is the difference between the 75th percentile
(Q3) and the 25th percentile (Q1), representing the spread of the middle 50% of the
data.

import numpy as np

arr = [Link]([10, 12, 12, 13, 12, 11, 300, 14, 13, 12])

# Calculate Q1 (25th percentile) and Q3 (75th percentile)


Q1 = [Link](arr, 25)
Q3 = [Link](arr, 75)
IQR = Q3 - Q1

# Define bounds
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

# Identify outliers
outliers = arr[(arr < lower_bound) | (arr > upper_bound)]

print("Outliers:", outliers)

Output:

Outliers: [ 10 300]

16. How do you remove missing or null values from a NumPy array?

We can remove null values using [Link]() method.

import numpy as np

my_array = [Link]([1, 2, [Link], 4, [Link], 6])

# Create a mask for NaN values


mask = [Link](my_array)

# Use the inverse of the mask to filter out missing values


filtered_array = my_array[~mask]

print("Original Array:", my_array)


Output:
print("Filtered Array (without NaNs):", filtered_array)

Original Array: [ 1. 2. nan 4. nan 6.]


Filtered Array (without NaNs): [1. 2. 4. 6.]

We can filter out missing or null data using a masked array or a boolean mask.

import numpy as np

# Create a NumPy array with missing values (NaN)


arr = [Link]([1.0, 2.0, [Link], 4.0, 5.0])

# Create a masked array where missing values are masked


masked_arr = [Link].masked_invalid(arr)

# Access only non-missing values


clean_data = masked_arr.compressed()

print(clean_data)

Output:

[1. 2. 4. 5.]

17. What is the difference between slicing and indexing in NumPy?

In NumPy, both slicing and indexing are fundamental operations for accessing and
manipulating elements in arrays, but there are some main difference are avialable.

Feature Slicing Indexing

Definition Extracts a range/subset of Accesses specific elements or subsets


elements from an array. from an array.

Syntax Uses a colon (:) inside square Uses square brackets with index values
brackets (e.g., arr[1:5]). (e.g., arr[2], arr[1, 3]).

Output Produces a contiguous block of Produces a single element or a set of


elements. specific elements.

Use Case When you want a continuous slice When you want random or specific
of data. positions.

Example arr[2:6] → elements from index 2 arr[0] → first element, arr[[1,3,5]] →


to 5. elements at indices 1, 3, and 5.

18. How can you create array with same values.


We can create a NumPy array with the same values using various functions and methods
depending on your specific needs. Here are a few common approaches:
1. Using [Link]():
You can use the [Link]() function to create an array filled with a specific value. This
function takes two arguments: the shape of the array and the fill value.

# Create a 1D array with 5 elements, all set to 7


arr = [Link](5, 7)

2. Using Broadcasting:
If you want to create an array of the same value repeated multiple times, you can use
broadcasting with NumPy.

# Create a 1D array with 5 elements, all set to 7


arr = 7 * [Link](5)

# Create a 2D array with dimensions 3x4, all elements set to 2.0


arr_2d = 2.0 * [Link]((3, 4))

3. Using list comprehension:


You can also create an array with the same values using a list comprehension and then
converting it to a NumPy array.

# Create a 1D array with 5 elements, all set to 7


arr = [Link]([7] * 5)

# Create a 2D array with dimensions 3x4, all elements set to 2.0


arr_2d = [Link]([[2.0] * 4] * 3)

19. What is a masked array in NumPy.

A masked array in NumPy is a special type of array that includes an additional Boolean
mask, which marks certain elements as invalid or masked. This allows you to work with
data that has missing or invalid values without having to modify the original data.
Masked arrays are particularly useful when dealing with real-world datasets that may
have missing or unreliable data points.

Example: Creating and Using a Masked Array

import numpy as np
import [Link] as ma

# Create a normal NumPy array


data = [Link]([1, 2, -999, 4, 5])

# Mask invalid values (-999 treated as missing data)


masked_data = ma.masked_equal(data, -999)
print("Original Data:", data)
print("Masked Data:", masked_data)

# Perform operations while ignoring masked values


mean_value = masked_data.mean()
print("Mean (ignoring masked values):", mean_value)

Output:

Original Data: [ 1 2 -999 4 5]


Masked Data: [1 2 -- 4 5]
Mean (ignoring masked values): 3.0

20. What is broadcasting in numpy?

Broadcasting in NumPy is the ability of NumPy to perform arithmetic operations on arrays


of different shapes and sizes without explicitly replicating the data.

If two arrays have different shapes, NumPy automatically expands the smaller array
along the mismatched dimensions so they can be combined.
This makes code more efficient and avoids unnecessary memory usage.

1. Broadcasting Scalar

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])

# Broadcasting scalar 10 across all elements


result = arr + 10
print(result)

Output:

[11 12 13 14 15]

2. Arrays with Different Shapes

# 2D array
A = [Link]([[1, 2, 3],
[4, 5, 6]])

# 1D array
B = [Link]([10, 20, 30])

# Broadcasting B across each row of A


result = A + B
print(result)

Output:

[[11 22 33]
[14 25 36]]

21. How do you sort a NumPy array in ascending or descending order?

To arrange a NumPy array in both ascending and descending order we use [Link]()
to create an ascending one and [Link]() for a descending one. Here’s how to do it:

1. Ascending Order: You can use the [Link]() function to sort your array in
ascending order. The function will return a new sorted array, while still leaving the
original array unchanged.

# Create a NumPy array


my_array = [Link]([3, 1, 2, 4, 5])

# Sort the array in ascending order


sorted_array = [Link](my_array)
print("Ascending: ",sorted_array)

Output:

Ascending: [1 2 3 4 5]

2. Sorting in Descending Order: To sort a NumPy array in descending order, you can use
the [Link]() function to obtain the indices that would sort the array in ascending
order and then reverse those indices to sort in descending order.

# Create a NumPy array


my_array = [Link]([3, 1, 2, 4, 5])

# Get indices for descending order and use them to reorder


descending_arr = arr[[Link](-arr)]
print("Descending:", descending_arr)

Output:

Descending: [ 5. 4. 3. 2. 1. nan]

22. How are NumPy Arrays better than Lists in Python?

NumPy arrays offer several advantages over Python lists when it comes to numerical and
scientific computing. Here are some key reasons why NumPy arrays are often preferred:

1. Performance
2. Vectorization
3. Broadcasting
4. Multidimensional Arrays
5. Memory Management
6. Standardization
23. Difference between [Link]() and [Link]()

Feature reshape() resize()

Definition Returns a new view or copy of Modifies the array itself (in-place) to match
the array with a new shape. the new shape.

Original Does not change the original


Array array unless inplace Changes the original array directly.
modification is forced.

Return Returns the reshaped array


Returns None (operation done in-place).
Value (new object).

Data Requires that the total number


If new size is bigger → fills with zeros. If
Handling of elements match the new
smaller → array is trimmed.
shape.

Memory Often returns a view (shares


Creates/reallocates memory if needed.
data) if possible, else a copy.

Use Case When you want a reshaped When you want to permanently change the
version of an array without shape of the array, even if padding or
altering the original. truncating is needed.

24. Discuss uses of vstack() and hstack() functions?

These functions are used for combining arrays in different dimensions and are widely
used in various data processing and manipulation tasks.

Feature vstack() hstack()

Definition Stacks arrays horizontally (column-


Stacks arrays vertically (row-wise).
wise).

Axis Operates along axis=0. Operates along axis=1.

Requirement Arrays must have the same Arrays must have the same number of
number of columns. rows.

Output
Increases the number of rows. Increases the number of columns.
Shape

Example [Link](([1,2,3], [4,5,6])) → [Link](([1,2,3], [4,5,6])) →


[[1,2,3],[4,5,6]] [1,2,3,4,5,6]
Feature vstack() hstack()

Use Case Useful when combining


Useful when combining data
features/variables for same data
points with same features.
points.

25. How to Get the eigen values and determinant of a matrix.

With the help of [Link]() method, we can get the eigen values of a matrix by using
[Link]() method.

[Link](matrix)

The Determinant of a square matrix is a unique number that can be derived from a square
matrix. Using the [Link]() method, NumPy gives us the ability to determine the
determinant of a square matrix.

[Link](array)

26. How to compare two NumPy arrays?

Method 1: Using == operator


We generally use the == operator to compare two NumPy arrays to generate a new array
object. Call [Link]() with the new array object as ndarray to return True if the two
NumPy arrays are equivalent.

import numpy as np

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([1, 2, 3])
arr3 = [Link]([1, 4, 3])

print((arr1 == arr2).all()) # True


print((arr1 == arr3).all()) # False

Output:

True
False

Method 2: Using array_equal()


This array_equal() function checks if two arrays have the same elements and same shape.

numpy.array_equal(arr1, arr2)
27. Calculate the QR decomposition of a given matrix using NumPy.

A matrix's decomposition into the form "A=QR," where Q is an orthogonal matrix and R is
an upper-triangular matrix and it is known as QR factorization. We can determine the QR
decomposition of a given using [Link]().

[Link](a, mode=’reduced’)

a: matrix(M,N) which needs to be factored.


mode: it is optional.

28. What are ndarrays in NumPy?

An ndarray also known as "N-dimensional array" is a fundamental data structure used in


NumPy for effectively storing and manipulating data, particularly numerical data. It is:

Multidimensional: Can represent 1D, 2D, 3D or higher-dimensional arrays.


Homogeneous: All elements must have the same data type.
Efficient: Optimized for mathematical and array-oriented operations.

29. What is Vectorization in Numpy?

Vectorization in NumPy means performing operations on entire arrays or vectors at once


without using explicit loops. NumPy internally uses optimized C code, so vectorized
operations are much faster than iterating through elements in Python.

Eliminates the need for for loops.


Operations are applied element-wise on the whole array.
Improves performance and makes code more concise.

import numpy as np

# Without vectorization (using loop)


arr = [Link]([1, 2, 3, 4, 5])
squared_loop = []
for x in arr:
squared_loop.append(x ** 2)
print("Using loop:", squared_loop)

# With vectorization
squared_vectorized = arr ** 2
print("Using vectorization:", squared_vectorized)

Output:

Using loop: [1, 4, 9, 16, 25]


Using vectorization: [ 1 4 9 16 25]
30. Difference between [Link](), view() and = assignment?

Feature = Assignment .view() .copy()

Definition Just creates a new Creates a shallow copy Creates a deep copy
reference to the same (new object but shares (new object with its
array object. same data buffer). own data).

Memory Same memory Completely


Different object, but data
location (no independent memory
points to the same memory.
duplication). allocation.

Object ID Different object IDs


Both variables have Different object IDs, but
and separate
the same object ID. share underlying data.
memory.

Effect of Changes in data reflect in


Changes in one array No effect as arrays
Changes both arrays, but attributes
reflect in the other. are independent.
like shape are independent.

Speed Fastest (no copy at Faster than deep copy ( just Slower (data
all). metadata copy). duplication happens).

Argument b=a b = [Link]() b = [Link]()

31. What is the difference between shape and size attributes of NumPy array.

Feature shape size

Definition Returns a tuple representing the Returns the total number of


dimensions of the array. elements in the array.

Type of Output Tuple for 2D arrays. Integer (single value).

Information Gives details about array


Gives overall element count,
Provided dimensions, like number of rows,
ignoring shape.
columns, etc.

Calculation Tuple shows the length along each Product of all dimensions in the
axis. shape tuple.

Argument [Link] → (3, 4) [Link] → 12

Use Case Useful to know the structure of the Useful to know the total elements
array. for operations like reshaping or
Feature shape size

flattening.

32. What is difference between python sequences, pandas array and numpy
array?

Feature Python Sequences NumPy Array Pandas


(list, tuple) (ndarray) Series/Array

Data Type Mostly homogeneous


Holds homogeneous
Can hold mixed data (like NumPy), but can
data (all elements of
types like [1, "a", 3.5]. also hold mixed or
same dtype).
object dtype.

Dimensionality Mostly 1D (lists/tuples).


Nested lists can Mainly 1D (Series) or
Supports n-
simulate higher 2D (DataFrame); built
dimensional arrays.
dimensions but on top of NumPy.
inefficient.

Performance Slightly slower than


Slower, not memory- Fast, memory-efficient NumPy due to extra
efficient (pure Python (C-based features but
objects). implementation). optimized for labeled
data.

Indexing Supports advanced Supports indexing +


Zero-based indexing indexing, slicing, labels, powerful
and supports slicing. boolean masking, alignment, missing
broadcasting. value handling.

Operations Vectorized operations


Element-wise Vectorized element-
(inherited from
operations require loops wise operations, linear
NumPy) + axis-aware
or comprehensions. algebra, broadcasting.
operations.

Use Case Numerical Data analysis, tabular


General-purpose computation, scientific data handling,
container. computing, machine missing values,
learning. statistics.

Arguments lst = [1, 2, 3] [Link]([1, 2, 3]) [Link]([1, 2, 3])

33. How would you convert a pandas dataframe into NumPy array.
You can use the DataFrame'[Link] attribute to convert a Pandas DataFrame into a
NumPy array.

import pandas as pd
import numpy as np

# Create a Pandas DataFrame (replace this with your actual DataFrame)


data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = [Link](data)

# Convert the DataFrame to a NumPy array


numpy_array = [Link]
print(numpy_array)

Output:

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

34. How would you reverse a numpy array?

We can reverse a NumPy array using the [::-1] slicing technique.

import numpy as np

# Create a NumPy array (replace this with your array)


original_array = [Link]([1, 2, 3, 4, 5])

# Reverse the array


reversed_array = original_array[::-1]

print(reversed_array)

Output:

[5 4 3 2 1]

35. Why NumPy is faster than list?

NumPy arrays are much faster than Python lists because of the way they are
implemented:

Homogeneous Data: NumPy arrays store elements of the same data type, unlike lists
that can store mixed types. This allows NumPy to use fixed-size memory blocks.
Contiguous Memory Allocation: NumPy stores data in continuous blocks of memory
making element access and operations faster due to better CPU cache utilization.
Vectorization: Operations in NumPy are implemented in C and use vectorized code, so
computations are applied to the whole array at once instead of looping in Python.
Low-Level Optimizations: NumPy relies on optimized C and Fortran libraries (like
BLAS, LAPACK) which are much faster than Python’s built-in loops.

import numpy as np
import time

# Using Python list


py_list = list(range(1, 1000000))
start = [Link]()
py_result = [x * 2 for x in py_list]
end = [Link]()
print("Python List Time:", end - start)

# Using NumPy array


np_array = [Link](1, 1000000)
start = [Link]()
np_result = np_array * 2
end = [Link]()
print("NumPy Array Time:", end - start)

Output:

Python List Time: 0.05335259437561035


NumPy Array Time: 0.004484653472900391

36. What is the procedure to count the number of times a given value appears in
an array of integers?

The bincount() function can be used to count the instances of a given value. It should be
noted that the bincount() function takes boolean expressions or positive integers as
arguments. Integers that are negative cannot be used.

arr = [Link]([0, 5, 4, 0, 4, 4, 3, 0, 0, 5, 2, 1, 1, 9])


[Link](arr)

37. How can you find the maximum or minimum value of an array in NumPy?

Using the max and min functions, we can determine array's maximum or minimum value
in NumPy. These operations accept an array as an input and output the array's maximum
or minimum value.

import numpy as np
# Create an array
arr = [Link]([3, 2, 1])
# Find the maximum value of the array
max_value = [Link](arr)
# Find the minimum value of the array
min_value = [Link](arr)
# Print the maximum and minimum values
print("max value: ",max_value)
print("min value: ",min_value)

Output:

max value: 3
min value: 1

38. How slicing and indexing can be used for data cleaning?

Both indexing and slicing are useful methods for cleaning data because they let you
modify or filter data based on particular criteria or target particular data points for
modification. In this example, negative values are located and replaced with zeros using
indexing and a new array with more than two members is created using slicing.

import numpy as np

# Sample NumPy array


data = [Link]([1, 2, -1, 4, 5, -2, 7])

# Indexing: Replace negative values with zeros


data[data < 0] = 0
print("After replacing negatives with zeros:", data)

# Slicing: Extract elements greater than 2


subset = data[data > 2]
print("Subset with elements greater than 2:", subset)

Output:

After replacing negatives with zeros: [1 2 0 4 5 0 7]


Subset with elements greater than 2: [4 5 7]

39. How can you find the unique elements in an array in NumPy?

Apply the unique function from the NumPy module to identify the unique elements in an
array in NumPy. This function returns the array's unique elements in sorted order.

import numpy as np
array = [Link]([1, 2, 3, 1, 2, 3, 3, 4, 5, 6, 7, 5])
unique = [Link](array)
print(unique)

Output:

[1 2 3 4 5 6 7]

Comment K kartik 6

You might also like