Unit 13 subjective questions NumPy and Pandas
ECAP792 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define Python and explain why it is widely used in data science.
Model answer
Python is a high-level, interpreted, general-purpose programming language known for its simple and readable syntax.
Python is widely used in data science because:
- Ease of learning: Its syntax is concise and easy to understand.
- Rich ecosystem: Libraries such as NumPy, Pandas, Matplotlib, and Scikit-learn support scientific computing and data analysis.
- Interactivity: Tools such as Jupyter Notebook allow code, output, and documentation to be combined.
- Community support: Python has extensive documentation and a large developer community.
- Integration: It can interact with databases, web applications, and languages such as C and C++.
Thus, Python enables analysts to perform the complete data science workflow, from data collection and cleaning to modeling and visualization.
-
Question 2 of 20
Describe the main built-in data structures in Python and give a suitable use case for each.
Model answer
The main built-in Python data structures are:
- List: An ordered, mutable collection that permits duplicate values. It is suitable for storing a sequence that may change, such as
scores = [75, 82, 91]. - Tuple: An ordered, immutable collection. It is useful for fixed records, such as
point = (4, 7). - Dictionary: A mutable collection of key-value pairs. It is suitable for labeled data, such as
student = {'name': 'Asha', 'marks': 90}. - Set: An unordered collection of unique values. It is useful for removing duplicates or performing union and intersection operations.
Lists and tuples are generally accessed by position, dictionaries by key, and sets through membership tests and set operations.
- List: An ordered, mutable collection that permits duplicate values. It is suitable for storing a sequence that may change, such as
-
Question 3 of 20
What is NumPy? Explain the important features of a NumPy
ndarray.Model answer
NumPy, or Numerical Python, is a Python library for efficient numerical and scientific computing. Its central object is the multidimensional array called
ndarray.Important features of an
ndarrayinclude:- It stores elements of a single homogeneous data type.
- It supports one-dimensional and multidimensional data.
- Its
shapespecifies the size along each axis. - Its
ndimgives the number of dimensions. - Its
sizegives the total number of elements. - Its
dtypeidentifies the element data type. - It supports vectorized calculations, broadcasting, slicing, aggregation, and linear algebra.
Because the data is stored compactly and operations are implemented in optimized compiled code, NumPy arrays are generally faster and more memory-efficient than Python lists for numerical work.
-
Question 4 of 20
Compare Python lists and NumPy arrays with respect to data type, memory usage, speed, and operations.
Model answer
Python lists and NumPy arrays differ in several ways:
Feature Python list NumPy array Data type May contain mixed types Normally contains one homogeneous type Memory Stores references and object metadata Uses compact, fixed-type storage Speed Element-wise loops execute in Python Vectorized operations use optimized compiled code Arithmetic list1 + list2concatenates listsarray1 + array2performs element-wise additionDimensions Nested lists represent dimensions indirectly Native support for multidimensional arrays For example, multiplying a list by
2repeats it, whereas multiplying a NumPy array by2doubles every element. Lists are appropriate for general-purpose heterogeneous collections, while arrays are preferable for large numerical datasets. -
Question 5 of 20
Explain different methods of creating NumPy arrays, with suitable examples.
Model answer
NumPy provides several array-creation methods:
- From a Python sequence:
np.array([1, 2, 3]) - Array of zeros:
np.zeros((2, 3)) - Array of ones:
np.ones((3, 2)) - Array filled with a value:
np.full((2, 2), 7) - Evenly spaced integer-like values:
np.arange(0, 10, 2) - A fixed number of evenly spaced values:
np.linspace(0, 1, 5) - Identity matrix:
np.eye(3) - Random values:
np.random.random((2, 2))
The required
dtypecan be stated explicitly, as innp.array([1, 2, 3], dtype='float64'). The method should be selected according to the desired shape, value pattern, and data type. - From a Python sequence:
-
-
Question 6 of 20
Explain the concepts of shape, dimension, size, axes, and reshaping in NumPy.
Model answer
For a NumPy array:
- Dimension (
ndim) is the number of axes. - Shape (
shape) is a tuple containing the length of each axis. - Size (
size) is the total number of elements. - Axis identifies a direction along which an operation is performed.
For an array with shape
(3, 4),ndimis2andsizeis . Axis0runs down the rows, while axis1runs across the columns.reshape()changes the arrangement without changing the element count. For example,a.reshape(3, 4)can transform a 12-element vector into a matrix. The condition is:Using
-1allows NumPy to infer one dimension, as ina.reshape(3, -1). Depending on memory layout, reshaping may return a view rather than an independent copy. - Dimension (
-
Question 7 of 20
Describe indexing, slicing, and Boolean masking in NumPy arrays. Include examples for one-dimensional and two-dimensional arrays.
Model answer
NumPy supports several forms of data selection:
- Basic indexing: For
a = np.array([10, 20, 30, 40]),a[1]returns20, anda[-1]returns40. - Slicing:
a[1:3]returns the elements at indices1and2. The general form isstart:stop:step, wherestopis excluded. - Two-dimensional indexing: If
mis a matrix,m[1, 2]selects the element in row1, column2;m[:, 0]selects the first column; andm[0:2, 1:3]selects a subarray. - Boolean masking:
a[a > 20]returns only values greater than20. - Fancy indexing:
a[[0, 3]]selects elements at explicitly listed positions.
Basic slices commonly return views, so modifying a slice may alter the original array. Boolean and fancy indexing generally return copies.
- Basic indexing: For
-
Question 8 of 20
What are vectorization and broadcasting in NumPy? Explain the broadcasting rules with examples.
Model answer
Vectorization means applying an operation to an entire array without writing an explicit Python loop. For example,
a * 2multiplies every element by2.Broadcasting allows NumPy to perform operations on arrays with compatible but different shapes. Dimensions are compared from right to left. Two dimensions are compatible when:
- They are equal, or
- One of them is
1.
For example, an array with shape
(3, 4)can be added to an array with shape(4,); the second array is treated as though it were repeated across the three rows. Similarly, shapes(3, 1)and(1, 4)broadcast to(3, 4).Shapes
(3, 4)and(2,)are incompatible because the trailing dimensions4and2are unequal and neither is1.Vectorization and broadcasting make code shorter and typically faster while avoiding unnecessary explicit data replication.
-
Question 9 of 20
Explain data types in Python and distinguish dynamically typed Python objects from fixed-type NumPy arrays.
Model answer
Python is dynamically typed, meaning a variable name can refer to objects of different types at different times. For example,
xcan first refer to an integer and later to a string. Built-in types includeint,float,complex,bool,str, andNoneType.Each Python object stores both its value and type-related metadata. A Python collection such as a list can therefore contain mixed objects, but this flexibility introduces memory and processing overhead.
A NumPy array normally uses a fixed data type, represented by
dtype, such asint32,float64, orbool. Its elements have a common size and memory representation. This enables:- Compact storage
- Predictable numerical behavior
- Fast vectorized operations
- Efficient interaction with compiled code
Thus, Python objects emphasize flexibility, while NumPy arrays emphasize efficient homogeneous numerical computation.
-
Question 10 of 20
Describe NumPy data types, type inference, type casting, and the possible risks of conversion.
Model answer
NumPy supports data types such as signed and unsigned integers, floating-point numbers, complex numbers, Boolean values, strings, and objects. Examples include
int8,int32,uint16,float32,float64,complex128, andbool.When
np.array()is called without adtype, NumPy infers a common type. For example, combining integers and floating-point values normally produces a floating-point array. A type can also be specified explicitly withdtype.Conversion can be performed using
astype(), such asa.astype('float64'). Important risks include:- Converting floats to integers discards the fractional part.
- Storing a value outside an integer type's range can cause overflow or rejection, depending on the operation.
- Converting higher-precision values to lower precision can lose information.
- Mixed strings and numbers may force an unintended string or object type.
The
dtypeshould therefore be selected according to range, precision, memory, and computational requirements. -
Question 11 of 20
What is Pandas? Explain the structure and major differences between a
Seriesand aDataFrame.Model answer
Pandas is a Python library that provides labeled data structures and tools for data cleaning, transformation, aggregation, and analysis.
A Series is a one-dimensional labeled array. It contains:
- A sequence of values
- An associated index
- A single
dtype - An optional name
A DataFrame is a two-dimensional labeled table. It contains:
- Rows identified by an index
- Columns identified by labels
- Potentially different data types across columns
- Multiple Series aligned on a shared row index
A Series is suitable for one variable, while a DataFrame represents a complete tabular dataset. For example, one column of student marks can be a Series, whereas a table containing names, marks, and grades is a DataFrame.
-
Question 12 of 20
Explain how Pandas
Seriesobjects can be created from lists, dictionaries, scalar values, and NumPy arrays.Model answer
A Pandas Series can be created in several ways:
- From a list:
pd.Series([10, 20, 30])creates a default integer index. - From a list with labels:
pd.Series([10, 20], index=['a', 'b'])creates a custom index. - From a dictionary:
pd.Series({'a': 10, 'b': 20})uses dictionary keys as index labels. - From a scalar:
pd.Series(5, index=['a', 'b', 'c'])repeats the scalar for every supplied label. - From a NumPy array:
pd.Series(np.array([1.5, 2.5]))uses the array values.
Useful Series attributes include
values,index,dtype,name,shape, andsize. Explicit labels should be unique where possible because duplicate labels can make selection and alignment less intuitive. - From a list:
-
Question 13 of 20
Explain data selection in a Pandas
Seriesusing bracket notation,loc,iloc, slicing, and Boolean masks.Model answer
Data in a Series can be selected as follows:
- Bracket notation:
s['a']selects the value labeleda. - Label-based selection:
s.loc['a']explicitly selects by label. - Position-based selection:
s.iloc[0]selects the first value by integer position. - Label slicing:
s.loc['a':'c']usually includes both endpoints. - Position slicing:
s.iloc[0:3]excludes the stop position, following normal Python slicing. - Boolean masking:
s[s > 50]returns values satisfying the condition. - Multiple labels:
s.loc[['a', 'c']]selects the listed labels.
Using
locandilocavoids ambiguity when the Series has integer labels. For example, label0and position0may refer to different selection concepts even when they happen to identify the same item. - Bracket notation:
-
Question 14 of 20
Describe different ways to create a Pandas
DataFrameand explain the role of its row index and column labels.Model answer
A DataFrame can be created from:
- A dictionary of lists:
pd.DataFrame({'name': ['A', 'B'], 'score': [80, 90]}) - A dictionary of Series: Values are aligned according to their Series indices.
- A list of dictionaries: Each dictionary usually represents one row.
- A two-dimensional NumPy array: Row and column labels can be supplied separately.
- External data: Functions such as
pd.read_csv()andpd.read_excel()load tabular files.
The row index identifies records, while column labels identify variables. Labels permit meaningful selection and automatic alignment. If custom labels are not provided, Pandas creates a
RangeIndex. A suitable index can improve readability and selection, but it does not replace the need to maintain valid and meaningful data columns. - A dictionary of lists:
-
Question 15 of 20
Explain data selection in a Pandas
DataFrameusing column selection,loc,iloc, slicing, and conditional filtering.Model answer
A DataFrame supports multiple selection methods:
df['age']returns one column as a Series.df[['name', 'age']]returns selected columns as a DataFrame.df.loc['r1']selects a row by label.df.loc['r1':'r3', ['name', 'age']]selects labeled rows and columns; the label slice normally includes its endpoint.df.iloc[0]selects the first row by position.df.iloc[0:3, 1:4]selects rows and columns by positional slices, excluding stop positions.df[df['score'] >= 50]filters rows using a Boolean condition.(df['age'] > 18) & (df['city'] == 'Pune')combines conditions using element-wise logical operators.
Parentheses are required around individual compound conditions.
locshould be used for labels and Boolean masks, whileilocshould be used for integer positions. -
Question 16 of 20
Distinguish between
loc,iloc,at, andiatin Pandas. When should each indexer be used?Model answer
The four indexers differ as follows:
Indexer Selection basis Typical purpose locRow and column labels Selecting ranges, lists of labels, or Boolean masks ilocInteger positions Selecting by positional indices and slices atA row label and column label Fast access to one scalar value iatA row position and column position Fast positional access to one scalar value Examples include
df.loc['r1', 'score'],df.iloc[0, 2],df.at['r1', 'score'], anddf.iat[0, 2].loclabel slices normally include the final label, whileilocslices exclude the stop position.atandiatare intended for a single value rather than selecting multiple rows or columns. -
Question 17 of 20
What is missing data in Pandas? Explain how Pandas represents and detects missing values.
Model answer
Missing data represents an unavailable, unknown, or inapplicable value. Pandas may represent it using:
NaNfor many numerical and object-based columnsNaTfor missing date or time valuespd.NAfor nullable extension data typesNone, which Pandas may convert or interpret as missing depending on the column type
Missing values can be detected using:
df.isna()ordf.isnull()to produce a Boolean maskdf.notna()ordf.notnull()to identify present valuesdf.isna().sum()to count missing values in each columndf.info()to inspect non-null counts and data types
Direct equality checks such as
value == np.nanshould not be used becauseNaNis not equal to itself. Missingness should be tested withisna()ornotna(). -
Question 18 of 20
Explain how
dropna()is used to handle missing data. Discuss the effects ofaxis,how,thresh, andsubset.Model answer
dropna()removes rows or columns according to missing-value rules.axis=0removes rows, whileaxis=1removes columns.how='any'removes an item if at least one selected value is missing.how='all'removes an item only if all selected values are missing.thresh=nretains an item only when it contains at leastnnon-missing values.subset=['a', 'b']limits the missing-value test to particular columns when rows are being removed.
For example,
df.dropna(subset=['target'])removes rows whose target value is absent, whiledf.dropna(axis=1, thresh=80)retains columns having at least 80 non-missing values.Dropping data is simple but may reduce sample size or introduce bias. The analyst should examine the amount and pattern of missingness before removing records or variables.
-
Question 19 of 20
Describe different strategies for filling missing values in Pandas using
fillna(), forward filling, backward filling, and statistical imputation.Model answer
Missing values can be filled using several strategies:
- Constant replacement:
df['city'].fillna('Unknown') - Mean imputation:
df['score'].fillna(df['score'].mean()) - Median imputation: Useful for skewed numerical data because it is less sensitive to outliers.
- Mode imputation: Suitable for categorical or discrete values.
- Forward filling:
df.ffill()uses the last observed value. - Backward filling:
df.bfill()uses the next observed value. - Grouped imputation: A value may be filled using a statistic computed within its category or group.
- Interpolation:
df.interpolate()estimates values between observations, especially in ordered numerical or time-series data.
The strategy must match the meaning and structure of the data. Forward and backward filling are appropriate only when observation order matters. Imputation preserves rows but can distort distributions, variance, and relationships, so the chosen method should be documented.
- Constant replacement:
-
Question 20 of 20
Design and explain a Pandas workflow for inspecting, selecting, cleaning, and summarizing a dataset containing missing values.
Model answer
A systematic Pandas workflow can include the following steps:
- Load data: Use a function such as
pd.read_csv(). - Inspect structure: Examine
df.head(),df.shape,df.columns,df.info(), anddf.describe(). - Check data types: Confirm that numerical, categorical, and date columns have suitable types; convert them where necessary.
- Detect missingness: Use
df.isna().sum()and calculate proportions withdf.isna().mean(). - Select relevant data: Use column lists,
loc,iloc, and Boolean filters. - Handle missing values: Drop unusable rows or columns, or impute values using constants, group statistics, filling, or interpolation.
- Validate cleaning: Recheck missing counts, ranges, duplicates, and data types.
- Summarize: Use operations such as
value_counts(),groupby(),agg(), anddescribe().
The workflow should avoid modifying the original data unexpectedly, justify every deletion or imputation, and verify that cleaning has not introduced invalid values or serious bias.
- Load data: Use a function such as
That's unit 13
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 13 of ECAP792 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 13 of ECAP792 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.