Unit 5: Handling Data with Pandas; Data Visualisation with Matplotlib - Practice Quiz
1 What is Pandas primarily used for in Python?
2 Which is the conventional way to import the Pandas library?
import pandas as pd
import pandas.pd
import pd as pandas
include pandas as pd
3 Pandas is built on top of which numerical computing library?
4 A Pandas Series is best described as a:
5 Which function is used to create a Pandas Series?
pd.Series()
pd.array()
pd.DataFrame()
pd.series()
6 What is the default index for a Series created from a list of 4 elements?
7 A Pandas DataFrame is a:
8
Which method displays the first 5 rows of a DataFrame df by default?
df.first()
df.head()
df.start()
df.top()
9 Which attribute gives the number of rows and columns of a DataFrame as a tuple?
df.length
df.dimensions
df.size
df.shape
10 Which Pandas function reads data from a CSV file into a DataFrame?
pd.read_csv()
pd.import_csv()
pd.load_csv()
pd.open_csv()
11
Which method writes a DataFrame df to a CSV file?
df.export_csv()
df.to_csv()
df.save_csv()
df.write_csv()
12 What does CSV stand for?
13 Which method provides summary statistics like mean, min, and max for numeric columns?
df.stats()
df.summary()
df.describe()
df.info()
14
How do you select a single column named age from a DataFrame df?
df->age
df['age']
df.get('age', all=True)
df.column('age')
15 Which method is used to remove rows containing missing (NaN) values?
df.deletena()
df.dropna()
df.removeNaN()
df.clearna()
16 Which Matplotlib function is used to create a line plot?
plt.graph()
plt.plot()
plt.line()
plt.draw()
17 Which function creates a figure with multiple subplots at once?
plt.figures()
plt.multiplot()
plt.grid()
plt.subplots()
18 A histogram is mainly used to show the:
19 Which Matplotlib function creates a vertical bar chart?
plt.barh()
plt.hist()
plt.bar()
plt.column()
20 A pie chart is best suited for showing:
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?
22
Given s = pd.Series([10, 20, 30], index=['a', 'b', 'c']), what does s['b'] return?
30
20
['b', 20]
10
23
What is the result of pd.Series([1, 2, 3]) + pd.Series([10, 20], index=[0, 2])?
NaN due to alignment
24
For a DataFrame df, which expression selects only the rows where the column age is greater than 30?
df[df.age.filter(> 30)]
df.loc['age' > 30]
df['age' > 30]
df[df['age'] > 30]
25
What does df.shape return for a DataFrame with 100 rows and 5 columns?
[100, 5]
(100, 5)
(5, 100)
500
26
Which method would you use to view the first 5 rows of a DataFrame df?
df.first(5)
df.head()
df.begin()
df.top()
27
You have a CSV file where columns are separated by semicolons (;). Which call reads it correctly?
pd.read_csv('data.csv', split=';')
pd.read_csv('data.csv', sep=';')
pd.read_csv('data.csv', delim=';')
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?
df.to_csv('out.csv', header=False)
df.to_csv('out.csv', index=False)
df.save_csv('out.csv', index=0)
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?
skiprows=1
header=0
names=True
header=None
30
Given a DataFrame df with a numeric column sales, which expression computes the average of that column?
df['sales'].average()
df['sales'].mean()
mean(df['sales'])
df.mean('sales')
31
What does df.groupby('city')['sales'].sum() produce?
32
Which method returns the count of missing (NaN) values in each column of a DataFrame df?
df.missing().sum()
df.isnull().sum()
df.isnull().count()
df.dropna().sum()
33
You want to create a new column total equal to price multiplied by quantity. Which statement is correct?
df['total'] = df['price'].mul()
df['total'] = df['price'] * df['quantity']
df.total = multiply(price, quantity)
df.add('total', price * quantity)
34
Using matplotlib, which pair of calls plots y against x as a line and then displays it?
plt.plot(y, x); plt.render()
plt.lineplot(x, y); plt.show()
plt.line(x, y); plt.draw()
plt.plot(x, y); plt.show()
35
In plt.plot(x, y, 'r--'), what does the format string 'r--' specify?
36 Which call creates a figure with a 2-row by 2-column grid of subplots?
fig, ax = plt.figure(2, 2)
fig, ax = plt.subplot(2, 2)
fig, ax = plt.subplots(2, 2)
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?
axes[1, 1].plot(...)
axes[2, 2].plot(...)
axes(1, 1).plot(...)
axes['bottom-right'].plot(...)
38
Which parameter of plt.hist(data, bins=20) controls the number of intervals the data range is divided into?
intervals
range
width
bins
39 A histogram is most appropriate for visualizing which of the following?
40
You have categories in a list cats and their counts in vals. Which call creates a vertical bar chart?
plt.barh(cats, vals)
plt.plot(cats, vals, 'bar')
plt.bar(cats, vals)
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']?
s['a':'b'] excludes 'b' because all Python slicing is exclusive of the endpoint
s[0:2] raises a KeyError since integer indexing is disabled when labels exist
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]?
df.loc[0] selects the row with index label 0; df.iloc[0] selects the first physical row (label 2)
df.loc[0] raises an error because the index is not sorted
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?
NaN (no alignment match); row 'b' holds the element-wise sum
ValueError due to mismatched indices
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?
Int64, because pandas always uses nullable integer types by default
float64, because NaN (a float) forces the entire integer column to be upcast to float
int64, because pandas fills missing integers with 0 automatically
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?
axis=0 returns one sum per column (collapsing rows); axis=1 returns one sum per row (collapsing columns)
axis=0 returns per-row sums; axis=1 returns per-column sums
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)?
how='all' drops rows with any NaN; how='any' drops only fully-NaN rows
how='all' drops a row only if every value is NaN; how='any' drops a row if at least one value is NaN
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?
plot call overwrites and erases the first line
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?
ax[2][2], using 1-based row and column numbers
ax.bottom_right, using the named-position attribute
ax[1, 1], because ax is a 2D NumPy array of Axes indexed by [row, column]
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?
50
What is the fundamental difference between plt.bar() and plt.hist()?
hist is just an alias for bar
bar() plots one bar per categorical/discrete value you supply; hist() bins continuous data and plots frequencies of those bins
bar() bins continuous data automatically while hist() requires pre-counted categories
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?
autopct rotates the chart; wedge sizes come from raw values without normalization
autopct controls wedge color; sizes are determined by insertion order only
autopct formats each wedge's percentage label; wedge angles are proportional to each value divided by the total
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?
Series can fall back to the object dtype, storing Python objects of mixed types, though at the cost of vectorized performance
Series cannot hold mixed types; it always raises an error like NumPy
Series stores each element in a separate NumPy array of its own dtype
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()?
transform drops the grouping while mean keeps every original row
transform returns a Series aligned to the original rows (each row gets its group mean); mean returns one aggregated value per group
transform returns a scalar; mean returns a full DataFrame
54
What is the effect of pd.read_csv('data.csv', index_col=0) versus omitting index_col?
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
index_col causes the last column to be used as the index by default
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?
df['col'] returns a 1D Series; df[['col']] returns a single-column DataFrame (2D)
df[['col']] raises an error because double brackets are invalid syntax
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?
57
For s = pd.Series([1, 2, 3]), why does s + pd.Series([1, 2, 3], index=[1, 2, 3]) produce NaN values?
NaN appears because the two Series have different lengths
NaN
NaN
58
In plt.hist(data, bins=20, density=True), what does density=True change about the y-axis?
density only affects bar color
59
Given time-series x values that are unsorted, what visual artifact does plt.plot(x, y) produce and why?
plot connects points in the order given, not in sorted x-order
60
What does df.merge(other, on='key', how='outer') produce compared to how='inner'?
outer concatenates rows vertically without matching on keys
outer keeps only matching keys; inner keeps everything
outer keeps all keys from both frames (filling unmatched sides with NaN); inner keeps only keys present in both
how only reorders columns
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 →