Unit 8 subjective questions NumPy functions
ECAP776 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define NumPy universal functions. Explain their main features with suitable examples.
Model answer
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], whilenp.add(a, 5)returns[6, 7, 8]. -
Question 2 of 20
Explain the arithmetic functions provided by NumPy. How do they differ from ordinary Python arithmetic on lists?
Model answer
NumPy provides arithmetic functions such as
np.add(),np.subtract(),np.multiply(),np.divide(),np.power(),np.mod(), andnp.remainder().For
a = np.array([2, 4, 6])andb = 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
2repeats it, whereas multiplying a NumPy array by2doubles every element. -
Question 3 of 20
Describe NumPy trigonometric functions and explain how angles can be converted between degrees and radians.
Model answer
NumPy includes trigonometric functions such as
np.sin(),np.cos(),np.tan(),np.arcsin(),np.arccos(), andnp.arctan().These functions normally accept angles in radians. The conversion formulas are:
NumPy provides
np.deg2rad()ornp.radians()for conversion to radians andnp.rad2deg()ornp.degrees()for conversion to degrees. For example,np.sin(np.deg2rad(30))produces approximately0.5. -
Question 4 of 20
Explain exponential, logarithmic, square-root, and absolute-value functions in NumPy with examples.
Model answer
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.]. Forb = np.array([-5, 0, 5]),np.abs(b)returns[5, 0, 5]. -
Question 5 of 20
Compare
np.floor(),np.ceil(),np.trunc(), andnp.round().Model answer
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.
-
-
Question 6 of 20
Explain the use of
np.sum(),np.prod(),np.cumsum(), andnp.cumprod(). Illustrate how theaxisparameter affects their results.Model answer
np.sum()andnp.prod()calculate aggregate sums and products, whilenp.cumsum()andnp.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=0reduces rows and produces one result per column, whileaxis=1reduces columns and produces one result per row. -
Question 7 of 20
Define mean, median, and weighted average. Explain how NumPy calculates them.
Model answer
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), andnp.average(a, weights=w). Unlikenp.mean(),np.average()supports explicit weights. -
Question 8 of 20
Derive the formulas for variance and standard deviation, and explain how
ddofaffects NumPy calculations.Model answer
For values with mean , population variance is:
Population standard deviation is:
NumPy calculates these using
np.var(a)andnp.std(a). Their default isddof=0, so the divisor is .For a sample, an unbiased variance estimate commonly uses:
This is obtained with
np.var(a, ddof=1)andnp.std(a, ddof=1). In general, NumPy uses the divisor . -
Question 9 of 20
Explain minimum, maximum, range, peak-to-peak, and the functions used to locate extreme values in a NumPy array.
Model answer
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 is3, the maximum is11, the range is ,np.argmin(a)is1, andnp.argmax(a)is2. -
Question 10 of 20
Describe percentiles and quantiles. Explain how they are computed in NumPy and state their relationship.
Model answer
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)andnp.quantile(a, 0.75)represent the same point. The 50th percentile is the median. -
Question 11 of 20
How are missing values handled by NumPy statistical functions? Compare regular functions with their
nanvariants.Model answer
A
NaNvalue represents missing or undefined numerical data. Regular statistical functions generally propagate it. For example,np.mean([2, np.nan, 4])returnsnan.NumPy provides functions that ignore
NaNvalues: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. -
Question 12 of 20
Explain
np.sort()and discuss sorting by axis in one-dimensional and two-dimensional arrays.Model answer
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.
-
Question 13 of 20
Distinguish between
np.sort()andnp.argsort(). How cannp.argsort()be used to reorder related data?Model answer
np.sort(a)returns the sorted values, whereasnp.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
namesandscoreshave corresponding positions,order = np.argsort(scores)allows both to be arranged consistently usingscores[order]andnames[order]. -
Question 14 of 20
Explain stable sorting and the
kindparameter of NumPy sorting functions. Why can sorting stability be important?Model answer
A sorting algorithm is stable if elements with equal keys retain their original relative order.
NumPy sorting functions accept a
kindparameter. 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. -
Question 15 of 20
Describe
np.lexsort()and explain how it performs indirect sorting using multiple keys.Model answer
np.lexsort()performs a stable indirect sort using multiple keys and returns sorting indices rather than sorted values.If
first_nameandlast_nameare arrays,np.lexsort((first_name, last_name))sorts primarily bylast_nameand usesfirst_nameto 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.
-
Question 16 of 20
Explain the different forms of
np.where(). Show how it can be used both for locating and conditionally replacing values.Model answer
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, andymay use broadcasting when their shapes are compatible. -
Question 17 of 20
Compare
np.nonzero(),np.argwhere(), andnp.flatnonzero().Model answer
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, whilenp.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
Trueis treated as nonzero andFalseas zero. -
Question 18 of 20
Describe
np.searchsorted(). Explain the meaning ofside="left"andside="right", and state its main precondition.Model answer
np.searchsorted(a, v)finds insertion positions that would preserve the order of a sorted one-dimensional arraya.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])andv = 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.
-
Question 19 of 20
Explain
np.count_nonzero()and show how its result changes when an axis or condition is supplied.Model answer
np.count_nonzero(a)counts elements whose truth value is nonzero orTrue.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)returns2. Equivalent expressions includenp.sum(a > 2)because BooleanTruevalues behave like1during summation. -
Question 20 of 20
Compare
np.unique(),np.bincount(), andnp.histogram()as counting functions. State when each should be used.Model answer
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.
That's unit 8
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 8 of ECAP776 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 8 of ECAP776 save you a night before the exam?
Then you can help keep it free for the next batch. 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.