Unit 2: Pandas for Data Handling - Practice Quiz
1
In the Pandas library, what is a Series?
2
Which of the following best describes a Pandas DataFrame?
3 How do you create a simple Pandas DataFrame from a Python dictionary?
4 Which Pandas function is used to read data from a CSV file into a DataFrame?
pd.get_csv()
pd.load_csv()
pd.open_csv()
pd.read_csv()
5
To save a DataFrame named df to a CSV file named data.csv, which command should you use?
df.export_csv('data.csv')
pd.write_csv(df, 'data.csv')
df.to_csv('data.csv')
df.save_csv('data.csv')
6
Which method is used to display the first 5 rows of a DataFrame df?
df.show()
df.first()
df.top()
df.head()
7
What does the .shape attribute of a DataFrame return?
8 Which method provides a concise summary of a DataFrame, including the index dtype, column dtypes, non-null values, and memory usage?
df.details()
df.summary()
df.info()
df.describe()
9
How do you select a single column named 'Name' from a DataFrame df?
df.get('Name')
df['Name']
df.select('Name')
df.column('Name')
10
Which expression correctly filters a DataFrame df to show only the rows where the 'Age' column is greater than 25?
df.select('Age' > 25)
df[df['Age'] > 25]
df.where(Age > 25)
df.filter('Age' > 25)
11
What is the primary use of the .iloc[] indexer in a Pandas DataFrame?
12
Which library is most commonly used with Pandas for data visualization and is typically imported as plt?
13 A line plot is best suited for which of the following tasks?
14 Which type of plot is most appropriate for comparing the populations of different countries?
15 What is the primary purpose of a histogram?
16 A scatter plot is used to visualize the relationship between...
17 A pie chart is most effective for representing which of the following?
18 In Matplotlib, which function is used to add a label to the x-axis of a plot?
plt.xaxis()
plt.label_x()
plt.set_xlabel()
plt.xlabel()
19 To add a title to a Matplotlib plot, which function would you use?
plt.title('My Plot Title')
plt.set_heading('My Plot Title')
plt.header('My Plot Title')
plt.caption('My Plot Title')
20 Which Matplotlib function is commonly used to create a figure and a grid of subplots in a single call?
plt.subplot_grid()
plt.axes()
plt.create_plots()
plt.subplots()
21
You have two Pandas Series, s1 and s2, with different indices. What is the result of the operation s1 + s2?
import pandas as pd
s1 = pd.Series([10, 20], index=['a', 'b'])
s2 = pd.Series([100, 200], index=['b', 'c'])
result = s1 + s2
What will `result` look like?
b), and NaN is produced for non-matching indices (a, c).
[110, 220].
b is kept, resulting in a Series with one element: [120].
22
Which of the following code snippets correctly selects all rows from a DataFrame df where the 'age' is greater than 30 AND the 'city' is 'New York'?
df[df['age'] > 30 and df['city'] == 'New York']
df[(df['age'] > 30) & (df['city'] == 'New York')]
df.loc['age' > 30 & 'city' == 'New York']
df.query('age > 30 & city == "New York"')
23
You run df.info() and df.describe() on your DataFrame. What is the key difference in the information they provide?
describe() works only for numerical columns, while info() works only for object/categorical columns.
info() gives statistical summaries like mean and standard deviation, while describe() lists column data types and memory usage.
info() provides a concise summary including data types, non-null values, and memory usage, while describe() generates descriptive statistics for numerical columns.
info() is just a more verbose version of describe().
24
You are reading a CSV file that uses a semicolon (;) as a delimiter instead of a comma. The file also contains a data row in the first line, meaning it has no header. Which pd.read_csv() call is most appropriate?
pd.read_csv('data.csv', sep=';', header=None)
pd.read_csv('data.csv', sep=',', header=False)
pd.read_csv('data.csv', separator=';', skiprows=1)
pd.read_csv('data.csv', delimiter=',', header=0)
25
Given the setup fig, ax = plt.subplots(2, 2, figsize=(8, 8)), how would you access the Axes object for the plot in the top-right corner to set its title?
plt.subplot(2, 2, 2).set_title('Top Right Plot')
ax[0, 1].set_title('Top Right Plot')
ax(0, 1).set_title('Top Right Plot')
ax[1, 0].set_title('Top Right Plot')
26
What is the primary purpose of a histogram, and what does the bins parameter control?
bins controls the width of the bars.
bins controls the number of data points to display.
bins controls the size of the markers.
bins controls the number of intervals the data is divided into.
27
Consider a DataFrame df. If you execute result = df.loc[df['Score'] > 90, 'Name'], what will be the data type of the result object, assuming multiple students have scores over 90?
28
What is the output of the following code snippet?
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
df['C'] = df['A'] * 2
df.iloc[0, 0] = 100
print(df.loc[0, 'C'])
29 Which code snippet correctly creates a line plot and adds a title, an x-axis label, and a y-axis label using the object-oriented Matplotlib approach?
fig, ax = plt.subplots() ax.plot(x, y).set_title('Title').set_xlabel('X-axis').set_ylabel('Y-axis')
fig, ax = plt.subplots() ax.plot(x, y) ax.title('Title') ax.xlabel('X-axis') ax.ylabel('Y-axis')
plt.plot(x, y) plt.title('Title') plt.xlabel('X-axis') plt.ylabel('Y-axis')
fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Title') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis')
30
In the call df.plot(kind='scatter', x='income', y='age', c='num_children', cmap='viridis'), what is the role of the c='num_children' argument?
31
You have a DataFrame df and you want to save it to a CSV file named 'data.csv' without including the default integer index. Which command should you use?
df.to_csv('data.csv', header=False)
df.save_csv('data.csv', index=False)
df.to_csv('data.csv', index=False)
df.to_csv('data.csv', no_index=True)
32
What is the fundamental difference between selecting data with df.loc and df.iloc?
loc includes the end of a slice (e.g., 0:5 includes index 5), while iloc excludes it.
loc can only select rows, while iloc can select both rows and columns.
loc is primarily label-based (it uses index and column names), while iloc is integer position-based.
iloc is a newer, faster version of loc with identical syntax.
33 Under which of the following circumstances is a pie chart generally considered an ineffective or poor choice for data visualization?
34
You have a DataFrame df with columns 'Region' and 'Revenue'. You want to create a bar plot showing the total revenue for each region. What is the most common and correct sequence of operations in Pandas?
df.plot(kind='bar', x='Region', y='Revenue').
35
You have a column df['product_type'] in your dataset. Which Pandas method is the most direct way to get a list of all the unique product types and their corresponding frequencies?
df['product_type'].value_counts()
df.groupby('product_type').count()
df['product_type'].describe()
df['product_type'].unique()
36 A line plot is most suitable for which of the following data visualization tasks?
37 How can you create a single plot that displays two different lines (e.g., from columns 'y1' and 'y2' against 'x') with different colors and a legend to identify them?
plt.plot(df['x'], [df['y1'], df['y2']]) plt.legend()
plt.plot(df['x'], df['y1']) plt.add_line(df['x'], df['y2']) plt.legend()
df.plot(x='x', y='y1', y2='y2')
plt.plot(df['x'], df['y1']) plt.plot(df['x'], df['y2']) plt.legend(['Series 1', 'Series 2'])
38
What is the primary benefit of using sharex=True or sharey=True when creating subplots with plt.subplots()?
39
In the Matplotlib object hierarchy, what is the relationship between a Figure and an Axes?
Figure is a single plotted line or bar, and an Axes is the collection of all figures in a plot.
Axes is just an older name for a Figure.
Axes object is the top-level container that can hold multiple Figure objects within it.
Figure is the overall window or canvas, and it contains one or more Axes objects, each of which represents an individual plot or chart.
40 What is the difference between a simple bar plot and a stacked bar plot?
41
Consider the following DataFrame with a MultiIndex:
python
import pandas as pd
import numpy as np
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
You want to select all rows where the first index level is 'bar' or 'foo', and for those rows, only where the second index level is 'two'. Which of the following lines of code achieves this selection correctly and most efficiently?
42
You have a DataFrame df and you execute the following commands:
python
df_slice = df.loc[df['A'] > 0]
df_slice['B'] = 999
Under which of the following conditions will the original DataFrame df be modified, and why?
df_slice is a view into df, so modifications propagate back.
df and will likely raise a SettingWithCopyWarning.
df_slice is always a copy when boolean indexing is used.
43
You are reading a large (10 GB) CSV file with a 'timestamp' column in ISO 8601 format (e.g., '2023-10-27T10:00:00Z') and a 'value' column. You only have 4 GB of RAM. Your goal is to compute the average 'value' for each calendar year. Which pd.read_csv strategy is most memory-efficient and correct for this task?
pd.read_csv(..., usecols=['timestamp', 'value']) to reduce memory, then convert the 'timestamp' column and group by year.
pd.read_csv(..., chunksize=100000, parse_dates=['timestamp']) and iterate through chunks, aggregating results in a dictionary.
pd.read_csv(..., low_memory=False) to force type inference on the whole file at once, then process.
pd.read_csv(..., converters={'timestamp': pd.to_datetime}), which will apply the conversion to the whole column before returning the DataFrame.
44
You want to create a figure with a complex layout: one large plot on the left spanning two rows, and two smaller plots stacked vertically on the right. You use the following code:
python
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6))
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[:, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])
Which line of code would correctly set the title of the top-right subplot to "Top Right" and the y-axis label of the large left subplot to "Value"?
45
You are analyzing a skewed dataset data and plot a histogram using plt.hist(data, bins=50). You then decide to apply a log transformation, log_data = np.log(data), and plot its histogram. What is the primary purpose and expected outcome of applying this transformation before plotting the histogram?
plt.xscale('log') on the original histogram.
46
You are given a DataFrame df with columns 'Category', 'SubCategory', and 'Sales'. You want to create a summary table that shows the total sales for each 'Category' as rows, each 'SubCategory' as columns, and fills any missing combinations with 0. Additionally, you need to include marginal totals (total sales for each category and each subcategory). Which of the following is the most direct and appropriate method?
df.pivot() to reshape the data, then manually calculate and append totals.
47
You are creating a line plot and want to add a horizontal dashed red line at the mean value of the data, and also add a text annotation slightly above this line. Given ax as your Matplotlib axes object and mean_val as the calculated mean, which code snippet correctly achieves this?
ax.text(x=0.5, y=mean_val + 5, s=f'Mean: {mean_val:.2f}', transform=ax.transAxes)
ax.annotate(f'Mean: {mean_val:.2f}', xy=(ax.get_xlim()[0], mean_val))
ax.text(x=ax.get_xlim()[0], y=mean_val * 1.05, s=f'Mean: {mean_val:.2f}')
plt.text(x=0, y=mean_val, s='Mean')
48
Given a DataFrame df, what is the functional difference between df.loc[df['A'] > 5] and df.query('A > 5') and when might you strongly prefer one over the other?
query() returns a view, preventing SettingWithCopyWarning.
query() evaluates the expression as a string, which can lead to better performance on very large DataFrames and allows for more complex, readable queries involving variable names with the @ prefix, but it does not support MultiIndex slicing as elegantly as .loc.
query() is just syntactic sugar for boolean indexing.
query() is significantly faster for small DataFrames, while boolean indexing is faster for large ones.
49
You have a pandas DataFrame df with a DatetimeIndex. You plot it using df['value'].plot(). You notice that there are gaps in your time series data (e.g., weekends are missing). When plotted, Matplotlib connects the data points across these gaps with a straight line. How can you create a line plot that shows these discontinuities, i.e., does not connect the points where data is missing?
df.plot(connect_missing=False).
df.plot(style='.') to create a scatter plot instead of a line plot.
50 You are creating a scatter plot to show the relationship between 'engine_size' and 'price' for a dataset of cars. You want the size of each point to represent the 'horsepower' and the color of each point to represent the 'fuel_type' (a categorical variable). Which code snippet correctly implements this?
51
You have a DataFrame df with columns 'Department', 'Gender', and 'Salary'. You want to create a grouped bar plot showing the average salary for each gender within each department. Which of the following approaches is the most direct way to generate the required data structure and plot it?
52
You are creating a pie chart from a pandas Series s that contains the market share of different companies. Some companies have a very small market share (<1%). To make the chart more readable, you want to group all these small companies into a single slice called 'Others'. Which sequence of operations correctly prepares the data for such a pie chart?
53
What is the primary difference between the pandas methods .apply() and .transform() when used on a GroupBy object, and in which scenario would .transform() be uniquely suitable?
.transform() can only be used with built-in aggregation functions like 'mean' or 'sum', whereas .apply() can use custom lambda functions.
.apply() works on columns, while .transform() works on rows.
.apply() can return a scalar, Series, or DataFrame, altering the shape of the output, while .transform() must return a Series that has the same index as the original DataFrame.
.transform() is a newer, faster version of .apply() with identical functionality.
54
When writing a DataFrame to a CSV file using df.to_csv('output.csv'), you observe that your floating-point numbers are being written with a large number of decimal places. How can you limit the precision of all floating-point numbers to 4 decimal places directly within the to_csv command?
to_csv.
55
You have plotted a pandas DataFrame and have the Matplotlib ax object. You want to change the format of the x-axis tick labels from numbers (e.g., 2023.0, 2023.25) to strings representing quarters (e.g., '2023-Q1', '2023-Q2'). Which of the following is the most robust way to achieve this using Matplotlib's functionality?
matplotlib.ticker.FuncFormatter to define a custom function that converts tick values to the desired string format and applying it to the x-axis.
56
Given a DataFrame df with a column 'A' of type object containing mostly integers but also some non-numeric strings ('error', 'missing'). You attempt to convert it to a numeric type using pd.to_numeric(df['A']) but it fails. What pd.to_numeric parameter setting allows you to convert valid numbers to numeric types while forcing all non-convertible values to NaN, without raising an error?
57
When creating two subplots with shared X and Y axes using fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True), what is the effect on the tick labels of the resulting plots?
ax2, and the Y-axis tick labels will only be visible on ax1.
ax1 and the Y-axis tick labels will be removed from ax2.
58
You have a DataFrame df with a non-unique index. What is the result of df.loc['duplicate_label'] versus df.iloc[0] if the first row has the label 'duplicate_label'?
df.loc['duplicate_label'] will raise a KeyError due to the non-unique index, while df.iloc[0] will succeed.
df.loc['duplicate_label'] returns a Series, and df.iloc[0] returns a DataFrame.
df.loc['duplicate_label'] returns a DataFrame containing all rows with that label, while df.iloc[0] returns a Series representing the first row.
59
What happens when you add two pandas Series with different indexes and what is the role of the fill_value parameter in the .add() method?
NaNs being propagated.
ValueError because the indexes do not align.
fill_value parameter allows you to specify a substitute value (e.g., 0) for missing elements during the alignment, preventing the propagation of NaN values.
60
In Matplotlib, what is the fundamental difference between the 'state-machine' interface (e.g., plt.plot()) and the 'object-oriented' interface (e.g., ax.plot()), and why is the latter generally preferred for complex plots?
figure, axes) as objects.
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 →