Unit 2 - Practice Quiz

CSE273 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 In the Pandas library, what is a Series?

Series and Data Frame Easy
A. A one-dimensional labeled array capable of holding data of any type.
B. A function used for plotting data.
C. A special type of Python dictionary.
D. A two-dimensional labeled data structure with columns of potentially different types.

2 Which of the following best describes a Pandas DataFrame?

Series and Data Frame Easy
A. A single column of data.
B. A library for numerical computation in Python.
C. A single row of data.
D. A two-dimensional, size-mutable, and potentially heterogeneous tabular data structure.

3 How do you create a simple Pandas DataFrame from a Python dictionary?

Series and Data Frame Easy
A. pd.DataFrame(my_dict)
B. pd.create_frame(my_dict)
C. pd.Frame(my_dict)
D. pd.Series(my_dict)

4 Which Pandas function is used to read data from a CSV file into a DataFrame?

Reading and writing CSV file Easy
A. pd.read_csv()
B. pd.load_csv()
C. pd.open_csv()
D. pd.get_csv()

5 To save a DataFrame named df to a CSV file named data.csv, which command should you use?

Reading and writing CSV file Easy
A. df.to_csv('data.csv')
B. pd.write_csv(df, 'data.csv')
C. df.export_csv('data.csv')
D. df.save_csv('data.csv')

6 Which method is used to display the first 5 rows of a DataFrame df?

Inspecting Datasets Easy
A. df.top()
B. df.head()
C. df.show()
D. df.first()

7 What does the .shape attribute of a DataFrame return?

Inspecting Datasets Easy
A. A tuple representing the dimensionality (rows, columns).
B. A summary of the central tendency and dispersion.
C. The data types of each column.
D. The total number of cells in the DataFrame.

8 Which method provides a concise summary of a DataFrame, including the index dtype, column dtypes, non-null values, and memory usage?

Inspecting Datasets Easy
A. df.summary()
B. df.info()
C. df.details()
D. df.describe()

9 How do you select a single column named 'Name' from a DataFrame df?

Selecting and filtering data Easy
A. df.column('Name')
B. df.get('Name')
C. df['Name']
D. df.select('Name')

10 Which expression correctly filters a DataFrame df to show only the rows where the 'Age' column is greater than 25?

Selecting and filtering data Easy
A. df.filter('Age' > 25)
B. df.select('Age' > 25)
C. df.where(Age > 25)
D. df[df['Age'] > 25]

11 What is the primary use of the .iloc[] indexer in a Pandas DataFrame?

Selecting and filtering data Easy
A. To select data by integer-position.
B. To select data based on a conditional statement.
C. To select data by label.
D. To select a random sample of data.

12 Which library is most commonly used with Pandas for data visualization and is typically imported as plt?

Data Visualization using Matplotlib Easy
A. Matplotlib
B. NumPy
C. Seaborn
D. Plotly

13 A line plot is best suited for which of the following tasks?

Line plot Easy
A. Displaying the relationship between two different numerical variables.
B. Visualizing a trend in data over a continuous interval or time period.
C. Comparing values across different categories.
D. Showing the distribution of a single numerical variable.

14 Which type of plot is most appropriate for comparing the populations of different countries?

Bar plot Easy
A. Line plot
B. Histogram
C. Scatter plot
D. Bar plot

15 What is the primary purpose of a histogram?

Histogram Easy
A. To compare values between different groups.
B. To show the relationship between two variables.
C. To show the frequency distribution of a single numerical variable.
D. To display parts of a whole.

16 A scatter plot is used to visualize the relationship between...

Scatter plot Easy
A. A variable and time.
B. Two numerical variables.
C. One numerical and one categorical variable.
D. Two categorical variables.

17 A pie chart is most effective for representing which of the following?

Pie chart Easy
A. Proportions or percentages of a whole.
B. The correlation between two variables.
C. Changes over a long period of time.
D. The distribution of a large dataset.

18 In Matplotlib, which function is used to add a label to the x-axis of a plot?

Customizing plots Easy
A. plt.label_x()
B. plt.xlabel()
C. plt.set_xlabel()
D. plt.xaxis()

19 To add a title to a Matplotlib plot, which function would you use?

Customizing plots Easy
A. plt.set_heading('My Plot Title')
B. plt.title('My Plot Title')
C. plt.header('My Plot Title')
D. 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?

Subplots Easy
A. plt.subplot_grid()
B. plt.subplots()
C. plt.axes()
D. plt.create_plots()

21 You have two Pandas Series, s1 and s2, with different indices. What is the result of the operation s1 + s2?

python
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?

Series and Data Frame Medium
A. The operation is performed element-wise by position, resulting in [110, 220].
B. An error is raised because the indices do not match.
C. Only the intersecting index b is kept, resulting in a Series with one element: [120].
D. The Series are aligned by index. The sum is computed for matching indices (b), and NaN is produced for non-matching indices (a, c).

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'?

Selecting and filtering data Medium
A. df.query('age > 30 & city == "New York"')
B. df[(df['age'] > 30) & (df['city'] == 'New York')]
C. df[df['age'] > 30 and df['city'] == 'New York']
D. df.loc['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?

Inspecting Datasets Medium
A. Both methods provide the same information; info() is just a more verbose version of describe().
B. describe() works only for numerical columns, while info() works only for object/categorical columns.
C. info() gives statistical summaries like mean and standard deviation, while describe() lists column data types and memory usage.
D. info() provides a concise summary including data types, non-null values, and memory usage, while describe() generates descriptive statistics for numerical columns.

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?

Reading and writing CSV file Medium
A. pd.read_csv('data.csv', sep=',', header=False)
B. pd.read_csv('data.csv', sep=';', header=None)
C. pd.read_csv('data.csv', separator=';', skiprows=1)
D. 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?

Subplots Medium
A. ax(0, 1).set_title('Top Right Plot')
B. ax[1, 0].set_title('Top Right Plot')
C. plt.subplot(2, 2, 2).set_title('Top Right Plot')
D. ax[0, 1].set_title('Top Right Plot')

26 What is the primary purpose of a histogram, and what does the bins parameter control?

Histogram Medium
A. To compare values across different categories; bins controls the width of the bars.
B. To show a trend over a continuous time period; bins controls the number of data points to display.
C. To show the relationship between two numerical variables; bins controls the size of the markers.
D. To display the frequency distribution of a single numerical variable; 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?

Selecting and filtering data Medium
A. A Pandas DataFrame with one column
B. A Pandas Series
C. A NumPy array
D. A Python list of names

28 What is the output of the following code snippet?

python
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'])

Series and Data Frame Medium
A. 200
B. 100
C. 2
D. An error is raised.

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?

Customizing plots Medium
A. fig, ax = plt.subplots() ax.plot(x, y).set_title('Title').set_xlabel('X-axis').set_ylabel('Y-axis')
B. fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Title') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis')
C. fig, ax = plt.subplots() ax.plot(x, y) ax.title('Title') ax.xlabel('X-axis') ax.ylabel('Y-axis')
D. plt.plot(x, y) plt.title('Title') plt.xlabel('X-axis') plt.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?

Scatter plot Medium
A. It maps the color of each point to the corresponding value in the 'num_children' column, using the 'viridis' colormap.
B. It sets the color of all points to a single color named 'num_children'.
C. It creates separate plots (facets) for each unique value in the 'num_children' column.
D. It uses the 'num_children' column to determine the size of each point.

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?

Reading and writing CSV file Medium
A. df.save_csv('data.csv', index=False)
B. df.to_csv('data.csv', header=False)
C. df.to_csv('data.csv', index=False)
D. df.to_csv('data.csv', no_index=True)

32 What is the fundamental difference between selecting data with df.loc and df.iloc?

Selecting and filtering data Medium
A. iloc is a newer, faster version of loc with identical syntax.
B. loc includes the end of a slice (e.g., 0:5 includes index 5), while iloc excludes it.
C. loc can only select rows, while iloc can select both rows and columns.
D. loc is primarily label-based (it uses index and column names), while iloc is integer position-based.

33 Under which of the following circumstances is a pie chart generally considered an ineffective or poor choice for data visualization?

Pie chart Medium
A. When comparing the proportions of 15 different categories, some of which have very similar values.
B. When showing the market share of two competing companies.
C. When displaying the percentage breakdown of a budget into 4-5 distinct categories.
D. When representing parts of a whole where the total sums to 100%.

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?

Bar plot Medium
A. First, group the DataFrame by 'Region' and calculate the sum of 'Revenue', then create a bar plot from the result.
B. First, sort the DataFrame by 'Revenue', then plot.
C. Create a pivot table with 'Region' as index and 'Revenue' as columns, then plot.
D. Directly plot using 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?

Inspecting Datasets Medium
A. df.groupby('product_type').count()
B. df['product_type'].value_counts()
C. df['product_type'].describe()
D. df['product_type'].unique()

36 A line plot is most suitable for which of the following data visualization tasks?

Line plot Medium
A. Showing the change in a country's population over several decades.
B. Displaying the proportion of different transportation methods used by commuters.
C. Comparing the sales figures of five different products in a single quarter.
D. Visualizing the distribution of employee ages within a company.

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?

Customizing plots Medium
A. plt.plot(df['x'], [df['y1'], df['y2']]) plt.legend()
B. plt.plot(df['x'], df['y1']) plt.plot(df['x'], df['y2']) plt.legend(['Series 1', 'Series 2'])
C. df.plot(x='x', y='y1', y2='y2')
D. plt.plot(df['x'], df['y1']) plt.add_line(df['x'], df['y2']) plt.legend()

38 What is the primary benefit of using sharex=True or sharey=True when creating subplots with plt.subplots()?

Subplots Medium
A. It creates a single, shared legend for all the subplots in the figure.
B. It forces all subplots to use the same color palette and styling.
C. It links the corresponding axes across the subplots, so that zooming/panning one affects the others, and it reduces clutter by hiding redundant tick labels.
D. It ensures that each subplot receives an identical copy of the data, preventing modification in one plot from affecting another.

39 In the Matplotlib object hierarchy, what is the relationship between a Figure and an Axes?

Data Visualization using Matplotlib Medium
A. A Figure is a single plotted line or bar, and an Axes is the collection of all figures in a plot.
B. They are the same thing; Axes is just an older name for a Figure.
C. A Figure is the overall window or canvas, and it contains one or more Axes objects, each of which represents an individual plot or chart.
D. An Axes object is the top-level container that can hold multiple Figure objects within it.

40 What is the difference between a simple bar plot and a stacked bar plot?

Bar plot Medium
A. A simple bar plot is vertical, while a stacked bar plot is horizontal.
B. A simple bar plot compares totals across categories, while a stacked bar plot shows the total and also breaks down that total into sub-category contributions within each bar.
C. A stacked bar plot can only be used for two categories, while a simple bar plot can be used for many.
D. There is no difference; they are just different names for the same type of plot generated by different software.

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?

Selecting and filtering data Hard
A. df.loc[(['bar', 'foo'], 'two'), :]
B. df.loc[pd.IndexSlice[['bar', 'foo'], 'two'], :]
C. df.query("first in ['bar', 'foo'] and second == 'two'")
D. df.loc[df.index.get_level_values('first').isin(['bar', 'foo']) & (df.index.get_level_values('second') == 'two')]

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?

Series and Data Frame Hard
A. It is ambiguous and depends on the internal memory layout of the DataFrame; this operation may or may not modify df and will likely raise a SettingWithCopyWarning.
B. Only if column 'B' is of a numeric data type; string columns are immutable.
C. Always, because df_slice is a view into df, so modifications propagate back.
D. Never, because 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?

Reading and writing CSV file Hard
A. Use pd.read_csv(..., usecols=['timestamp', 'value']) to reduce memory, then convert the 'timestamp' column and group by year.
B. Use pd.read_csv(..., chunksize=100000, parse_dates=['timestamp']) and iterate through chunks, aggregating results in a dictionary.
C. Use pd.read_csv(..., converters={'timestamp': pd.to_datetime}), which will apply the conversion to the whole column before returning the DataFrame.
D. Load the file with pd.read_csv(..., low_memory=False) to force type inference on the whole file at once, then process.

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"?

Subplots Hard
A. ax1.set_title("Top Right"); ax3.set_ylabel("Value")
B. fig.axes[1].set_title("Top Right"); fig.axes[0].set_ylabel("Value")
C. gs[0, 1].set_title("Top Right"); gs[:, 0].set_ylabel("Value")
D. ax2.set_title("Top Right"); ax1.set_ylabel("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?

Histogram Hard
A. To convert the frequency counts on the y-axis into probabilities, making the total area of the histogram equal to 1.
B. To change the x-axis to a logarithmic scale, which is equivalent to calling plt.xscale('log') on the original histogram.
C. To normalize the data such that its histogram approximates a Gaussian (Normal) distribution, making patterns and central tendency easier to visualize.
D. To decrease the number of bins required to represent the data, improving performance.

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?

Inspecting Datasets Hard
A. df.pivot_table(values='Sales', index='Category', columns='SubCategory', aggfunc='sum', fill_value=0, margins=True, margins_name='Total')
B. First, use df.pivot() to reshape the data, then manually calculate and append totals.
C. pd.crosstab(index=df['Category'], columns=df['SubCategory'], values=df['Sales'], aggfunc='sum', margins=True, margins_name='Total').fillna(0)
D. df.groupby(['Category', 'SubCategory'])['Sales'].sum().unstack(fill_value=0)

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?

Customizing plots Hard
A. plt.hlines(y=mean_val, xmin=0, xmax=1, color='r')
plt.text(x=0, y=mean_val, s='Mean')
B. ax.axhline(y=mean_val, color='r', linestyle='--')
ax.text(x=0.5, y=mean_val + 5, s=f'Mean: {mean_val:.2f}', transform=ax.transAxes)
C. ax.hlines(y=mean_val, color='r', linestyle='--')
ax.annotate(f'Mean: {mean_val:.2f}', xy=(ax.get_xlim()[0], mean_val))
D. ax.axhline(y=mean_val, color='r', linestyle='--')
ax.text(x=ax.get_xlim()[0], y=mean_val * 1.05, s=f'Mean: {mean_val:.2f}')

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?

Selecting and filtering data Hard
A. 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.
B. query() is significantly faster for small DataFrames, while boolean indexing is faster for large ones.
C. There is no functional difference; query() is just syntactic sugar for boolean indexing.
D. Boolean indexing returns a copy, whereas query() returns a view, preventing SettingWithCopyWarning.

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?

Line plot Hard
A. Set df.plot(style='.') to create a scatter plot instead of a line plot.
B. Use df.plot(connect_missing=False).
C. This is the default behavior and cannot be changed in the standard pandas plotting function.
D. Reindex the DataFrame with a complete date range and then plot. The missing values (NaNs) will not be plotted.

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?

Scatter plot Hard
A. df.plot.scatter(x='engine_size', y='price', s='horsepower', c='fuel_type', colormap='viridis')
B. df.plot.scatter(x='engine_size', y='price', s=df['horsepower'], c=pd.factorize(df['fuel_type'])[0], colormap='viridis')
C. plt.scatter(x=df['engine_size'], y=df['price'], size=df['horsepower'], color=df['fuel_type'].astype('category').cat.codes, cmap='viridis')
D. plt.scatter(x=df['engine_size'], y=df['price'], s=df['horsepower'], c=df['fuel_type'])

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?

Bar plot Hard
A. df.groupby(['Department', 'Gender'])['Salary'].mean().plot(kind='bar')
B. df.pivot_table(values='Salary', index='Department', columns='Gender', aggfunc='mean').plot(kind='bar', stacked=True)
C. pd.crosstab(df.Department, df.Gender).plot(kind='bar')
D. df.pivot_table(values='Salary', index='Department', columns='Gender', aggfunc='mean').plot(kind='bar')

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?

Pie chart Hard
A. s.apply(lambda x: 'Others' if x < 0.01 else x).groupby().sum().plot.pie()
B. s_new = s[s >= 0.01]; s_new['Others'] = s[s < 0.01].sum(); s_new.plot.pie()
C. s[s < 0.01] = s[s < 0.01].sum(); s.plot.pie()
D. s_others = s.where(s >= 0.01, 'Others'); s_others.plot.pie()

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?

Series and Data Frame Hard
A. .transform() is a newer, faster version of .apply() with identical functionality.
B. .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.
C. .apply() works on columns, while .transform() works on rows.
D. .transform() can only be used with built-in aggregation functions like 'mean' or 'sum', whereas .apply() can use custom lambda functions.

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?

Reading and writing CSV file Hard
A. df.to_csv('output.csv', precision=4)
B. df.to_csv('output.csv', float_format='%.4f')
C. This is not possible; you must round the data in the DataFrame before calling to_csv.
D. df.round(4).to_csv('output.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?

Data Visualization using Matplotlib Hard
A. ax.xaxis.set_major_formatter('%Y-Q%q')
B. By using matplotlib.ticker.FuncFormatter to define a custom function that converts tick values to the desired string format and applying it to the x-axis.
C. This requires re-creating the plot with a custom index in the DataFrame.
D. ax.set_xticklabels(['2023-Q1', '2023-Q2', '2023-Q3', '2023-Q4'])

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?

Inspecting Datasets Hard
A. pd.to_numeric(df['A'], downcast='integer')
B. pd.to_numeric(df['A'], errors='coerce')
C. pd.to_numeric(df['A'], errors='raise')
D. pd.to_numeric(df['A'], errors='ignore')

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?

Subplots Hard
A. Both subplots will display all tick labels on both their X and Y axes.
B. The X-axis tick labels will only be visible on ax2, and the Y-axis tick labels will only be visible on ax1.
C. The tick labels are unaffected, but the axis limits are linked.
D. The X-axis tick labels will be removed from 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'?

Selecting and filtering data Hard
A. df.loc['duplicate_label'] returns a Series, and df.iloc[0] returns a DataFrame.
B. Both will return a Series representing the first row.
C. df.loc['duplicate_label'] returns a DataFrame containing all rows with that label, while df.iloc[0] returns a Series representing the first row.
D. df.loc['duplicate_label'] will raise a KeyError due to the non-unique index, while df.iloc[0] will succeed.

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?

Series and Data Frame Hard
A. The resulting Series contains the union of the indexes. For any index label not present in one of the Series, its value is treated as 0 during the addition, resulting in NaNs being propagated.
B. The resulting Series contains the union of the indexes. The 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.
C. The operation fails, raising a ValueError because the indexes do not align.
D. The resulting Series contains the intersection of the indexes, discarding any labels not present in both.

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?

Customizing plots Hard
A. The state-machine interface can only create basic plot types, while the object-oriented interface is required for advanced plots like 3D or polar plots.
B. There is no functional difference, only a stylistic one preferred by different programmers.
C. The state-machine interface implicitly acts on the 'current' figure and axes, making it difficult to manage multiple plots, whereas the object-oriented interface gives you explicit control over each plot element (figure, axes) as objects.
D. The state-machine interface is faster, while the object-oriented interface provides more customization options.