Unit 8: NumPy functions - Subjective Questions
ECAP776 • Practice Questions with Detailed Answers
20 questions
Define NumPy universal functions. Explain their main features with suitable examples.
NumPy universal functions, commonly called ufuncs, operate element by element on NumPy arrays.
Main features:
- They support fast vectorized computation.
- They can operate on arrays of different shapes through broadcasting.
- They usually return a new array without changing the original array.
- They are faster than equivalent Python loops.
For a = np.array([1, 2, 3]), np.square(a) returns [1, 4, 9], while np.add(a, 5) returns [6, 7, 8].
Explain the arithmetic functions provided by NumPy. How do they differ from ordinary Python arithmetic on lists?
NumPy provides arithmetic functions such as np.add(), np.subtract(), np.multiply(), np.divide(), np.power(), np.mod(), and np.remainder().
For a = np.array([2, 4, 6]) and b = np.array([1, 2, 3]):
np.add(a, b)gives[3, 6, 9].np.multiply(a, b)gives[2, 8, 18].np.power(a, b)gives[2, 16, 216].
Unlike Python lists, NumPy arrays perform element-wise arithmetic. For example, multiplying a Python list by 2 repeats it, whereas multiplying a NumPy array by 2 doubles every element.
Describe NumPy trigonometric functions and explain how angles can be converted between degrees and radians.
NumPy includes trigonometric functions such as np.sin(), np.cos(), np.tan(), np.arcsin(), np.arccos(), and np.arctan().
These functions normally accept angles in radians. The conversion formulas are:
NumPy provides np.deg2rad() or np.radians() for conversion to radians and np.rad2deg() or np.degrees() for conversion to degrees. For example, np.sin(np.deg2rad(30)) produces approximately 0.5.
Explain exponential, logarithmic, square-root, and absolute-value functions in NumPy with examples.
Important NumPy mathematical functions include:
np.exp(x): calculates .np.log(x): calculates the natural logarithm .np.log2(x): calculates the base-2 logarithm.np.log10(x): calculates the base-10 logarithm.np.sqrt(x): calculates .np.absolute(x)ornp.abs(x): calculates .
For a = np.array([1, 4, 9]), np.sqrt(a) returns [1., 2., 3.]. For b = np.array([-5, 0, 5]), np.abs(b) returns [5, 0, 5].
Compare np.floor(), np.ceil(), np.trunc(), and np.round().
These functions process decimal values differently:
np.floor(x)returns the greatest integer less than or equal to .np.ceil(x)returns the smallest integer greater than or equal to .np.trunc(x)removes the fractional part and moves toward zero.np.round(x, decimals)rounds to the specified number of decimal places.
For :
np.floor(x)gives-3.0.np.ceil(x)gives-2.0.np.trunc(x)gives-2.0.np.round(x)gives-3.0.
Thus, floor and truncation differ especially for negative values.
Explain the use of np.sum(), np.prod(), np.cumsum(), and np.cumprod(). Illustrate how the axis parameter affects their results.
np.sum() and np.prod() calculate aggregate sums and products, while np.cumsum() and np.cumprod() calculate cumulative results.
For a = np.array([[1, 2], [3, 4]]):
np.sum(a)gives10.np.prod(a)gives24.np.sum(a, axis=0)gives[4, 6], representing column sums.np.sum(a, axis=1)gives[3, 7], representing row sums.np.cumsum([1, 2, 3])gives[1, 3, 6].np.cumprod([1, 2, 3])gives[1, 2, 6].
In a two-dimensional array, axis=0 reduces rows and produces one result per column, while axis=1 reduces columns and produces one result per row.
Define mean, median, and weighted average. Explain how NumPy calculates them.
The mean is the sum of observations divided by their number:
The median is the middle value after sorting; for an even number of observations, it is the mean of the two middle values.
A weighted average assigns a weight to each observation:
NumPy uses np.mean(a), np.median(a), and np.average(a, weights=w). Unlike np.mean(), np.average() supports explicit weights.
Derive the formulas for variance and standard deviation, and explain how ddof affects NumPy calculations.
For values with mean , population variance is:
Population standard deviation is:
NumPy calculates these using np.var(a) and np.std(a). Their default is ddof=0, so the divisor is .
For a sample, an unbiased variance estimate commonly uses:
This is obtained with np.var(a, ddof=1) and np.std(a, ddof=1). In general, NumPy uses the divisor .
Explain minimum, maximum, range, peak-to-peak, and the functions used to locate extreme values in a NumPy array.
np.min(a)finds the minimum value.np.max(a)finds the maximum value.- The range can be calculated as
np.max(a) - np.min(a). np.ptp(a)directly calculates the peak-to-peak range.np.argmin(a)returns the index of the first minimum value.np.argmax(a)returns the index of the first maximum value.
For a = np.array([8, 3, 11, 5]), the minimum is 3, the maximum is 11, the range is , np.argmin(a) is 1, and np.argmax(a) is 2.
Describe percentiles and quantiles. Explain how they are computed in NumPy and state their relationship.
A percentile divides ordered data into 100 parts. The th percentile is the value below which approximately of observations lie. A quantile expresses the same idea on a scale from to .
NumPy provides:
np.percentile(a, p)for a percentile between0and100.np.quantile(a, q)for a quantile between0and1.
Their relationship is:
For example, np.percentile(a, 75) and np.quantile(a, 0.75) represent the same point. The 50th percentile is the median.
How are missing values handled by NumPy statistical functions? Compare regular functions with their nan variants.
A NaN value represents missing or undefined numerical data. Regular statistical functions generally propagate it. For example, np.mean([2, np.nan, 4]) returns nan.
NumPy provides functions that ignore NaN values:
np.nanmean()calculates the mean of valid values.np.nanmedian()calculates the median of valid values.np.nanstd()andnp.nanvar()calculate standard deviation and variance.np.nanmin()andnp.nanmax()find valid extremes.np.nansum()calculates the sum while treatingNaNas zero.
Thus, np.nanmean([2, np.nan, 4]) gives . These functions are useful for incomplete numerical datasets.
Explain np.sort() and discuss sorting by axis in one-dimensional and two-dimensional arrays.
np.sort() returns a sorted copy of an array and normally leaves the original array unchanged.
For a one-dimensional array, np.sort([4, 1, 3]) returns [1, 3, 4].
For a two-dimensional array:
np.sort(a, axis=0)sorts values down each column.np.sort(a, axis=1)sorts values across each row.np.sort(a, axis=None)first flattens the array and then sorts all elements.
The default axis is the last axis, so rows are sorted independently in a typical two-dimensional array.
Distinguish between np.sort() and np.argsort(). How can np.argsort() be used to reorder related data?
np.sort(a) returns the sorted values, whereas np.argsort(a) returns the indices that would sort the array.
For a = np.array([30, 10, 20]):
np.sort(a)returns[10, 20, 30].np.argsort(a)returns[1, 2, 0].a[np.argsort(a)]reconstructs the sorted array.
The indices can also reorder related data. If names and scores have corresponding positions, order = np.argsort(scores) allows both to be arranged consistently using scores[order] and names[order].
Explain stable sorting and the kind parameter of NumPy sorting functions. Why can sorting stability be important?
A sorting algorithm is stable if elements with equal keys retain their original relative order.
NumPy sorting functions accept a kind parameter. Common choices include:
kind="quicksort"kind="heapsort"kind="stable"
Stable sorting is useful when data has already been ordered by another field. For example, after sorting student records by name, a stable sort by grade preserves alphabetical order among students with equal grades.
The exact internal algorithm used for kind="stable" can depend on the data type, but NumPy guarantees stable behavior.
Describe np.lexsort() and explain how it performs indirect sorting using multiple keys.
np.lexsort() performs a stable indirect sort using multiple keys and returns sorting indices rather than sorted values.
If first_name and last_name are arrays, np.lexsort((first_name, last_name)) sorts primarily by last_name and uses first_name to break ties. This is because the last key is the primary key.
The returned index array can be applied to every related column, ensuring that complete records remain aligned. It is useful for sorting tables by fields such as department, grade, and name.
Explain the different forms of np.where(). Show how it can be used both for locating and conditionally replacing values.
np.where() has two major forms:
np.where(condition)returns a tuple of index arrays identifying positions where the condition is true.np.where(condition, x, y)chooses elements fromxwhere the condition is true and fromyotherwise.
For a = np.array([-2, 0, 5, 7]):
np.where(a > 0)identifies indices2and3.np.where(a > 0, a, 0)returns[0, 0, 5, 7].np.where(a % 2 == 0, "even", "odd")performs element-wise classification.
The condition, x, and y may use broadcasting when their shapes are compatible.
Compare np.nonzero(), np.argwhere(), and np.flatnonzero().
All three functions identify nonzero elements, but they format indices differently:
np.nonzero(a)returns a tuple containing one index array for each dimension.np.argwhere(a)groups the coordinates of each nonzero element into rows.np.flatnonzero(a)returns indices into the flattened version of the array.
For a two-dimensional array, np.nonzero() is convenient for advanced indexing, while np.argwhere() is convenient when each coordinate must be processed as a pair. np.flatnonzero() is appropriate when only linear positions are required.
Boolean values are also supported because True is treated as nonzero and False as zero.
Describe np.searchsorted(). Explain the meaning of side="left" and side="right", and state its main precondition.
np.searchsorted(a, v) finds insertion positions that would preserve the order of a sorted one-dimensional array a.
side="left"returns the position before existing equal values.side="right"returns the position after existing equal values.
For a = np.array([1, 3, 3, 7]) and v = 3:
np.searchsorted(a, 3, side="left")returns1.np.searchsorted(a, 3, side="right")returns3.
Its main precondition is that the input array must already be sorted according to the expected order. It uses an efficient binary-search strategy and can search for several values at once.
Explain np.count_nonzero() and show how its result changes when an axis or condition is supplied.
np.count_nonzero(a) counts elements whose truth value is nonzero or True.
For a = np.array([[0, 2, 3], [4, 0, 0]]):
np.count_nonzero(a)returns3.np.count_nonzero(a, axis=0)returns[1, 1, 1], giving counts by column.np.count_nonzero(a, axis=1)returns[2, 1], giving counts by row.
Conditions can also be counted directly. For example, np.count_nonzero(a > 2) returns 2. Equivalent expressions include np.sum(a > 2) because Boolean True values behave like 1 during summation.
Compare np.unique(), np.bincount(), and np.histogram() as counting functions. State when each should be used.
These functions count data in different ways:
np.unique(a, return_counts=True)returns each distinct value and its frequency. It supports many sortable data types and is appropriate for general frequency tables.np.bincount(a)counts occurrences of each non-negative integer. The array index represents the value, so it is very efficient for dense integer categories but does not directly accept negative integers or floating-point categories.np.histogram(a, bins=...)counts numerical observations within intervals rather than counting exact values.
For [1, 1, 3], np.bincount() returns [0, 2, 0, 1]. For continuous measurements, a histogram is usually more meaningful because values are grouped into ranges. For arbitrary labels or exact-value frequencies, np.unique(..., return_counts=True) is the most flexible choice.
Define NumPy universal functions. Explain their main features with suitable examples.
NumPy universal functions, commonly called ufuncs, operate element by element on NumPy arrays.
Main features:
- They support fast vectorized computation.
- They can operate on arrays of different shapes through broadcasting.
- They usually return a new array without changing the original array.
- They are faster than equivalent Python loops.
For a = np.array([1, 2, 3]), np.square(a) returns [1, 4, 9], while np.add(a, 5) returns [6, 7, 8].
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →