Unit 5: Handling Data with Pandas; Data Visualisation with Matplotlib - Practice Quiz

ECE181 — Introduction To Python 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is Pandas primarily used for in Python?

introduction to pandas Easy
A. Managing operating system processes
B. Data manipulation and analysis
C. Compiling C++ code
D. Building 3D games

2 Which is the conventional way to import the Pandas library?

introduction to pandas Easy
A. import pandas as pd
B. import pandas.pd
C. import pd as pandas
D. include pandas as pd

3 Pandas is built on top of which numerical computing library?

introduction to pandas Easy
A. SciPy
B. NumPy
C. TensorFlow
D. Matplotlib

4 A Pandas Series is best described as a:

series Easy
A. Scalar single value
B. Two-dimensional labeled table
C. One-dimensional labeled array
D. Three-dimensional data cube

5 Which function is used to create a Pandas Series?

series Easy
A. pd.Series()
B. pd.array()
C. pd.DataFrame()
D. pd.series()

6 What is the default index for a Series created from a list of 4 elements?

series Easy
A. No index is assigned
B. Integers 1, 2, 3, 4
C. Letters a, b, c, d
D. Integers 0, 1, 2, 3

7 A Pandas DataFrame is a:

dataframe Easy
A. One-dimensional labeled array
B. Single scalar value
C. Plain Python dictionary
D. Two-dimensional labeled data structure

8 Which method displays the first 5 rows of a DataFrame df by default?

dataframe Easy
A. df.first()
B. df.head()
C. df.start()
D. df.top()

9 Which attribute gives the number of rows and columns of a DataFrame as a tuple?

dataframe Easy
A. df.length
B. df.dimensions
C. df.size
D. df.shape

10 Which Pandas function reads data from a CSV file into a DataFrame?

working with csv files Easy
A. pd.read_csv()
B. pd.import_csv()
C. pd.load_csv()
D. pd.open_csv()

11 Which method writes a DataFrame df to a CSV file?

working with csv files Easy
A. df.export_csv()
B. df.to_csv()
C. df.save_csv()
D. df.write_csv()

12 What does CSV stand for?

working with csv files Easy
A. Comma-Separated Values
B. Character-Set Values
C. Common Storage Version
D. Column-Sorted Values

13 Which method provides summary statistics like mean, min, and max for numeric columns?

operations using dataframes Easy
A. df.stats()
B. df.summary()
C. df.describe()
D. df.info()

14 How do you select a single column named age from a DataFrame df?

operations using dataframes Easy
A. df->age
B. df['age']
C. df.get('age', all=True)
D. df.column('age')

15 Which method is used to remove rows containing missing (NaN) values?

operations using dataframes Easy
A. df.deletena()
B. df.dropna()
C. df.removeNaN()
D. df.clearna()

16 Which Matplotlib function is used to create a line plot?

line plots Easy
A. plt.graph()
B. plt.plot()
C. plt.line()
D. plt.draw()

17 Which function creates a figure with multiple subplots at once?

multiple subplots in one figure Easy
A. plt.figures()
B. plt.multiplot()
C. plt.grid()
D. plt.subplots()

18 A histogram is mainly used to show the:

histograms Easy
A. Distribution of a numeric variable
B. Relationship between two categories
C. Trend over time only
D. Proportion of a whole

19 Which Matplotlib function creates a vertical bar chart?

bar charts Easy
A. plt.barh()
B. plt.hist()
C. plt.bar()
D. plt.column()

20 A pie chart is best suited for showing:

pie charts Easy
A. Proportions of a whole
B. Trends over time
C. Frequency distribution of bins
D. Correlation between variables

21 You import pandas using import pandas as pd. Which statement correctly describes why pandas is preferred over plain Python lists for tabular data analysis?

introduction to pandas Medium
A. It provides labeled, aligned data structures with vectorized operations
B. It stores data only as JSON internally for speed
C. It replaces the need for the NumPy library entirely
D. It compiles Python code into C for faster loops

22 Given s = pd.Series([10, 20, 30], index=['a', 'b', 'c']), what does s['b'] return?

series Medium
A. 30
B. 20
C. ['b', 20]
D. 10

23 What is the result of pd.Series([1, 2, 3]) + pd.Series([10, 20], index=[0, 2])?

series Medium
A. All values are added position by position ignoring the index
B. Values at index 1 become NaN due to alignment
C. It raises a length mismatch error
D. It concatenates into a Series of length 5

24 For a DataFrame df, which expression selects only the rows where the column age is greater than 30?

dataframe Medium
A. df[df.age.filter(> 30)]
B. df.loc['age' > 30]
C. df['age' > 30]
D. df[df['age'] > 30]

25 What does df.shape return for a DataFrame with 100 rows and 5 columns?

dataframe Medium
A. [100, 5]
B. (100, 5)
C. (5, 100)
D. 500

26 Which method would you use to view the first 5 rows of a DataFrame df?

dataframe Medium
A. df.first(5)
B. df.head()
C. df.begin()
D. df.top()

27 You have a CSV file where columns are separated by semicolons (;). Which call reads it correctly?

working with csv files Medium
A. pd.read_csv('data.csv', split=';')
B. pd.read_csv('data.csv', sep=';')
C. pd.read_csv('data.csv', delim=';')
D. pd.load_csv('data.csv', sep=';')

28 You want to save a DataFrame df to a CSV file without writing the index column. Which call is correct?

working with csv files Medium
A. df.to_csv('out.csv', header=False)
B. df.to_csv('out.csv', index=False)
C. df.save_csv('out.csv', index=0)
D. df.write_csv('out.csv', index=None)

29 When reading a CSV that has no header row, which argument ensures pandas does not treat the first data row as column names?

working with csv files Medium
A. skiprows=1
B. header=0
C. names=True
D. header=None

30 Given a DataFrame df with a numeric column sales, which expression computes the average of that column?

operations using dataframes Medium
A. df['sales'].average()
B. df['sales'].mean()
C. mean(df['sales'])
D. df.mean('sales')

31 What does df.groupby('city')['sales'].sum() produce?

operations using dataframes Medium
A. A count of rows per city
B. The sales sorted alphabetically by city
C. Total sales for each unique city
D. The overall sum of all sales values

32 Which method returns the count of missing (NaN) values in each column of a DataFrame df?

operations using dataframes Medium
A. df.missing().sum()
B. df.isnull().sum()
C. df.isnull().count()
D. df.dropna().sum()

33 You want to create a new column total equal to price multiplied by quantity. Which statement is correct?

operations using dataframes Medium
A. df['total'] = df['price'].mul()
B. df['total'] = df['price'] * df['quantity']
C. df.total = multiply(price, quantity)
D. df.add('total', price * quantity)

34 Using matplotlib, which pair of calls plots y against x as a line and then displays it?

line plots Medium
A. plt.plot(y, x); plt.render()
B. plt.lineplot(x, y); plt.show()
C. plt.line(x, y); plt.draw()
D. plt.plot(x, y); plt.show()

35 In plt.plot(x, y, 'r--'), what does the format string 'r--' specify?

line plots Medium
A. A rectangular line style
B. Two red solid lines
C. A red dashed line
D. A round dotted marker

36 Which call creates a figure with a 2-row by 2-column grid of subplots?

multiple subplots in one figure Medium
A. fig, ax = plt.figure(2, 2)
B. fig, ax = plt.subplot(2, 2)
C. fig, ax = plt.subplots(2, 2)
D. fig, ax = plt.grid(2, 2)

37 After fig, axes = plt.subplots(2, 2), how do you draw on the subplot in the bottom-right corner?

multiple subplots in one figure Medium
A. axes[1, 1].plot(...)
B. axes[2, 2].plot(...)
C. axes(1, 1).plot(...)
D. axes['bottom-right'].plot(...)

38 Which parameter of plt.hist(data, bins=20) controls the number of intervals the data range is divided into?

histograms Medium
A. intervals
B. range
C. width
D. bins

39 A histogram is most appropriate for visualizing which of the following?

histograms Medium
A. The exact value of each individual record
B. The relationship between two categorical variables
C. The proportion of parts in a whole
D. The frequency distribution of a single continuous variable

40 You have categories in a list cats and their counts in vals. Which call creates a vertical bar chart?

bar charts Medium
A. plt.barh(cats, vals)
B. plt.plot(cats, vals, 'bar')
C. plt.bar(cats, vals)
D. plt.hist(cats, vals)

41 Given s = pd.Series([10, 20, 30], index=['a', 'b', 'c']), what does s[0:2] return compared to s['a':'b']?

series Hard
A. Both return exactly the same two elements because slicing is always position-based
B. s['a':'b'] excludes 'b' because all Python slicing is exclusive of the endpoint
C. s[0:2] raises a KeyError since integer indexing is disabled when labels exist
D. s[0:2] returns elements at positions 0 and 1; s['a':'b'] returns elements 'a' and 'b' (label slicing is inclusive of endpoint)

42 For a DataFrame df, which statement correctly distinguishes df.loc[] from df.iloc[] when the index is [2, 0, 1]?

dataframe Hard
A. Both select the same row because index labels are ignored
B. df.loc[0] selects the row with index label 0; df.iloc[0] selects the first physical row (label 2)
C. df.loc[0] raises an error because the index is not sorted
D. df.iloc[0] selects the row labeled 0 and df.loc[0] selects the first physical row

43 Given df1 with index ['a','b'] and df2 with index ['b','c'], what is the result of df1 + df2 for overlapping and non-overlapping labels?

operations using dataframes Hard
A. Only row 'b' survives; rows 'a' and 'c' are dropped from the result
B. Rows 'a' and 'c' become NaN (no alignment match); row 'b' holds the element-wise sum
C. The operation raises a ValueError due to mismatched indices
D. All rows are summed positionally regardless of labels

44 A CSV has a column of integers but some cells are empty. After pd.read_csv('data.csv'), what dtype does that column typically have and why?

working with csv files Hard
A. Int64, because pandas always uses nullable integer types by default
B. float64, because NaN (a float) forces the entire integer column to be upcast to float
C. int64, because pandas fills missing integers with 0 automatically
D. object, because any missing value converts all numbers to strings

45 For a numeric DataFrame df, how do df.apply(np.sum, axis=0) and df.apply(np.sum, axis=1) differ?

operations using dataframes Hard
A. Both return a single scalar equal to the total sum of all elements
B. axis=0 returns one sum per column (collapsing rows); axis=1 returns one sum per row (collapsing columns)
C. axis=0 returns per-row sums; axis=1 returns per-column sums
D. axis=1 raises an error because np.sum only works column-wise

46 What is the key behavioral difference between df.dropna(how='all') and df.dropna(how='any') (default)?

dataframe Hard
A. how='all' drops rows with any NaN; how='any' drops only fully-NaN rows
B. Both drop identical rows; the parameter only changes performance
C. how='all' drops a row only if every value is NaN; how='any' drops a row if at least one value is NaN
D. how='all' fills NaN with the mean instead of dropping

47 When plotting plt.plot(x, y1); plt.plot(x, y2) on the same axes without specifying colors, what happens?

line plots Hard
A. Matplotlib automatically assigns different colors from the default color cycle to each line
B. Both lines are drawn in the same color, making them indistinguishable
C. The second plot call overwrites and erases the first line
D. A ValueError is raised because colors must be specified explicitly

48 Using fig, ax = plt.subplots(2, 2), how should you correctly access the subplot in the bottom-right position?

multiple subplots in one figure Hard
A. ax[2][2], using 1-based row and column numbers
B. ax.bottom_right, using the named-position attribute
C. ax[1, 1], because ax is a 2D NumPy array of Axes indexed by [row, column]
D. ax[3], because subplots are stored in a flat 1D list

49 For plt.hist(data, bins=10) on data ranging from 0 to 100, what determines each bin's width and count?

histograms Hard
A. The count is the cumulative total of all points up to that bin's upper edge
B. Each bin always contains exactly the same number of data points (equal-frequency binning)
C. Width is fixed at 1 unit regardless of the data range
D. Width is the range divided by bins (10 units each); count is the number of data points falling in each interval

50 What is the fundamental difference between plt.bar() and plt.hist()?

bar charts Hard
A. Both are identical; hist is just an alias for bar
B. bar() plots one bar per categorical/discrete value you supply; hist() bins continuous data and plots frequencies of those bins
C. bar() bins continuous data automatically while hist() requires pre-counted categories
D. bar() can only produce horizontal bars while hist() produces vertical ones

51 In plt.pie(sizes, autopct='%1.1f%%'), what does autopct control and how are wedge sizes determined?

pie charts Hard
A. autopct rotates the chart; wedge sizes come from raw values without normalization
B. autopct controls wedge color; sizes are determined by insertion order only
C. autopct formats each wedge's percentage label; wedge angles are proportional to each value divided by the total
D. autopct sets the number of wedges; wedge sizes are always equal

52 Why can a pandas Series hold heterogeneous data more flexibly than a plain NumPy array of a fixed numeric dtype?

introduction to pandas Hard
A. A Series can fall back to the object dtype, storing Python objects of mixed types, though at the cost of vectorized performance
B. A Series cannot hold mixed types; it always raises an error like NumPy
C. A Series stores each element in a separate NumPy array of its own dtype
D. A Series internally converts all values to strings to allow mixing types

53 Given df.groupby('cat')['val'].transform('mean'), how does its output differ from df.groupby('cat')['val'].mean()?

operations using dataframes Hard
A. transform drops the grouping while mean keeps every original row
B. transform returns a Series aligned to the original rows (each row gets its group mean); mean returns one aggregated value per group
C. transform returns a scalar; mean returns a full DataFrame
D. Both return one value per group with identical shape

54 What is the effect of pd.read_csv('data.csv', index_col=0) versus omitting index_col?

working with csv files Hard
A. Both produce identical results because the first column always becomes the index
B. With index_col=0, the first column becomes the DataFrame index; without it, a default RangeIndex (0,1,2,...) is created and all columns are kept as data
C. Omitting index_col causes the last column to be used as the index by default
D. index_col=0 skips the first column entirely rather than using it as an index

55 Which comparison of df['col'] and df[['col']] is correct?

dataframe Hard
A. df['col'] returns a 1D Series; df[['col']] returns a single-column DataFrame (2D)
B. df[['col']] raises an error because double brackets are invalid syntax
C. Both return a Series with identical shape and type
D. df['col'] returns a DataFrame; df[['col']] returns a Series

56 When fig, axes = plt.subplots(1, 3, sharey=True) is used, what does sharey=True accomplish?

multiple subplots in one figure Hard
A. Each subplot gets an independent y-axis automatically scaled to its own data
B. All three subplots share the same y-axis scale and limits, and inner y-tick labels are hidden for clarity
C. The y-data of the three plots is summed into a single shared plot
D. It forces all subplots to share the same x-axis instead of the y-axis

57 For s = pd.Series([1, 2, 3]), why does s + pd.Series([1, 2, 3], index=[1, 2, 3]) produce NaN values?

series Hard
A. NaN appears because the two Series have different lengths
B. The operation fails entirely and returns an empty Series
C. Labels are aligned before addition; only indices 1 and 2 overlap, so indices 0 and 3 yield NaN
D. Addition is positional, so all three pairs add cleanly with no NaN

58 In plt.hist(data, bins=20, density=True), what does density=True change about the y-axis?

histograms Hard
A. The y-axis shows cumulative counts up to each bin
B. The y-axis is unchanged; density only affects bar color
C. The y-axis shows raw counts multiplied by the number of bins
D. The y-axis shows probability density so the total area under the bars equals 1, rather than raw counts

59 Given time-series x values that are unsorted, what visual artifact does plt.plot(x, y) produce and why?

line plots Hard
A. Only the points are shown with no connecting line at all
B. The line zig-zags back and forth because plot connects points in the order given, not in sorted x-order
C. Matplotlib automatically sorts x before drawing, so the line is always smooth
D. It raises an error demanding sorted x-values

60 What does df.merge(other, on='key', how='outer') produce compared to how='inner'?

operations using dataframes Hard
A. outer concatenates rows vertically without matching on keys
B. outer keeps only matching keys; inner keeps everything
C. outer keeps all keys from both frames (filling unmatched sides with NaN); inner keeps only keys present in both
D. Both keep the same rows; how only reorders columns