100 Python MCQs for Data Analytics
100 Python MCQs for Data Analytics
Q4. You need a fast daily percent change in close for ABL as percentchange. What’s best?
A) ABL['percentchange']=ABL['close'].pct_change()*100
B) ABL['percentchange']=(ABL['close']/ABL['close'].shift())*100
C) ABL['percentchange']=ABL['close'].diff()
D) ABL['percentchange']=[Link](ABL['close']).diff()
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 2
Answer: A.
Explanation: pct_change() is vectorized and returns % change; multiply by 100 for percentage.
Q5. You must compute correlation of ABL vs MCB closing prices on aligned dates only. Best
approach?
A) ABL['close'].corr(MCB['close'])
B) [Link]([ABL['close'],MCB['close']],axis=1).corr()
C) Merge on date then corr of the two close columns
D) Inner join on index after set_index('date') then corr
Answer: C.
Explanation: You must align by the same trading dates; merging on date ensures that.
Q6. After reading CSVs, you find duplicate dates in MCB. The safest dedup keeping the last
record?
A) MCB.drop_duplicates()
B) MCB.drop_duplicates('date')
C) MCB.drop_duplicates(subset=['date'],keep='last')
D) MCB=MCB[~[Link]()]
Answer: C.
Explanation: Explicit subset with keep='last' preserves the newest corrected row.
Q7. To efficiently compute rolling 5-day median on MARI['close'] ignoring NaN:
A) MARI['close'].rolling(5).median()
B) MARI['close'].rolling(window=5,min_periods=1).mean()
C) MARI['close'].expanding().median()
D) [Link](MARI['close'],5)
Answer: A.
Explanation: Rolling median uses the specified window and skips NaN by default.
Q8. For memory efficiency before joins, you downcast volume to smallest integer that fits ≥0.
A) ABL['volume']=ABL['volume'].astype('int64')
B) pd.to_numeric(ABL['volume'],downcast='integer')
C) ABL['volume']=ABL['volume'].astype('uint8')
D) ABL['volume']=pd.Int64Dtype()
Answer: B.
Explanation: downcast='integer' picks minimal int type that fits values.
Q9. You want a vectorized NumPy way to cap MCB['change'] at ±10.
A) MCB['change']=[Link](MCB['change'],-10,10)
B) MCB['change']=MCB['change'].apply(lambda x: max(-10,min(10,x)))
C) MCB['change']=[max(-10,min(10,x)) for x in MCB['change']]
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 3
D) MCB['change']=MCB['change'].where(MCB['change']<=10,10)
Answer: A.
Explanation: [Link] is vectorized and fastest.
Q10. To sort UBL by date ascending after parsing dates:
A) UBL.sort_values('date',ascending=True,inplace=True)
B) UBL['date']=UBL['date'].astype(str).sort_values()
C) UBL.sort_index()
D) UBL['date']=pd.to_datetime(UBL['date']).sort_index()
Answer: A.
Explanation: Sorting by column directly is clear; ensure date parsed beforehand.
Q13. You must ensure no missing values remain afterward for all columns. Which check is
concise?
A) [Link]().sum()==0
B) [Link]().[Link]()
C) [Link]().sum().sum()==0
D) [Link]()
Answer: C.
Explanation: Summing null counts across frame equals zero confirms no missing values.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 4
Q14. During extract, CSV has numeric columns with thousand separators. Most robust read?
A) pd.read_csv(path, decimal=',')
B) pd.read_csv(path, thousands=',')
C) pd.read_csv(path, dtype=float)
D) pd.read_csv(path, converters={'close':float})
Answer: B.
Explanation: thousands=',' parses strings like “1,234” as numbers.
Q15. To ensure schema consistency across ABL/MARI/MCB/UBL before concatenation:
A) Just [Link]([ABL,MARI,MCB,UBL])
B) Align columns by reindexing all frames to a standard column list
C) Use append
D) Convert all to strings
Answer: B.
Explanation: Reindexing/renaming ensures identical column order/names.
Q16. You validate “date strictly increasing” after transform. Efficient check?
A) UBL['date'].is_monotonic_increasing
B) UBL['date'].diff().sum()>0
C) UBL['date'].duplicated().any()
D) UBL['date'].is_unique
Answer: A.
Explanation: .is_monotonic_increasing directly answers the monotonicity check.
Q17. In production ETL for auditability, what’s MOST important?
A) Obfuscating logs for security
B) Random sampling of rows
C) Deterministic transforms with versioned code and data lineage
D) Non-deterministic multithreading
Answer: C.
Explanation: Audit requires reproducibility, lineage, and version control.
Q18. For idempotent loads into a warehouse (no dupes on re-runs), best pattern?
A) Truncate-and-load always
B) Insert without checks
C) Upsert (merge on business keys)
D) CSV replace in place
Answer: C.
Explanation: Upserts keep targets correct across repeated runs.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 5
Q22. You want consistent styling across all plots for the report:
A) Set [Link]('seaborn') at top
B) Manually style each plot
C) Use random colors
D) Use rcParams per-plot
Answer: A.
Explanation: A global style ensures uniform look with minimal code.
Q23. To highlight a crash region (e.g., March 2020) in the time series:
A) [Link]([Link]('2020-03-01'), [Link]('2020-03-31'), alpha=0.2)
B) [Link](...)
C) plt.fill_between(y1=close,y2=0)
D) [Link](...)
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 6
Answer: A.
Explanation: axvspan shades a vertical time interval.
Q24. You must visualize distribution of percentchange with outliers:
A) [Link](...)
B) [Link](x='percentchange',data=ABL)
C) [Link](...)
D) [Link](...)
Answer: B.
Explanation: Boxplots are ideal to show spread and outliers.
Q25. To show rolling correlation of ABL vs MCB close over 60 days:
A) [Link](...)
B) Plot of rolling(60).corr() series
C) Bar chart of monthly correlation
D) Pairplot of all columns
Answer: B.
Explanation: Rolling correlation plotted as a line reveals time-varying relationships.
Q26. You need a small-multiple grid by ticker for close trends. Quickest?
A) [Link](kind='line',col='ticker',x='date',y='close',data=long_df)
B) Loop and create subplots manually
C) [Link](...)
D) [Link](kind='line',...)
Answer: A.
Explanation: relplot(..., col=...) creates facet gridlines by category.
C) ABL['close'].var()
D) ABL['close'].std()
Answer: B.
Explanation: Range is max–min.
Q29. You need robust dispersion less sensitive to outliers:
A) Standard deviation
B) Variance
C) Interquartile range (IQR)
D) Range
Answer: C.
Explanation: IQR focuses on the middle 50%.
Q30. To get Q1, median, Q3 quickly:
A) [Link](series,[.25,.5,.75])
B) [Link]()
C) [Link]()
D) [Link]()['std']
Answer: A.
Explanation: [Link] returns requested quantiles.
Q31. The change column is the difference in closing prices of successive days (per brief). A sanity
check expecting its mean to be near zero works best when:
A) Prices trend upward
B) Series is stationary or detrended
C) Any time series
D) Only with monthly data
Answer: B.
Explanation: Mean of differences is meaningful under stationarity/detrending.
Q32. To summarize by month the average percentchange for ABL:
A) Group by ABL['date'].[Link] then .mean()
B) resample('M')['percentchange'].mean() on a datetime index
C) pivot_table(index='month',values='percentchange')
D) rolling(30).mean()
Answer: B.
Explanation: Resampling on a datetime index is idiomatic and concise.
Q33. Volatility proxy for MARI['close'] over 30 days is best captured by:
A) 30-day mean
B) 30-day standard deviation of returns
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 8
Answer: B.
Explanation: Correlation indicates association, not causation.
Q38. To test whether mean daily return of UBL differs from zero (unknown variance):
A) One-sample z-test
B) One-sample t-test
C) Paired t-test
D) Wilcoxon signed-rank requires symmetry only
Answer: B.
Explanation: Use a one-sample t-test when σ unknown.
Q39. Multiple testing across four tickers inflates false positives. A quick control is:
A) Increase α to 10%
B) Bonferroni or FDR correction
C) Use fewer data points
D) Ignore p-values
Answer: B.
Explanation: Adjust for multiplicity to control Type I error.
Q40. Serial correlation in returns invalidates i.i.d. assumptions. First diagnostic?
A) ACF/PACF plots
B) KDE of returns
C) Boxplot
D) Heatmap
Answer: A.
Explanation: Autocorrelation functions test serial dependence.
Q41. To forecast next-day MCB close with only past closes, a simple baseline is:
A) Ordinary least squares on close levels
B) Random forest on raw prices
C) Naïve forecast: tomorrow = today
D) K-means clustering
Answer: C.
Explanation: Naïve random walk is a strong baseline in finance.
Q42. If you regress ABL returns on MCB returns and find β≈0.8 (significant), interpretation?
A) 1% MCB move associates with ~0.8% ABL move
B) ABL leads MCB by one day
C) Perfect hedge
D) No effect
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 10
Answer: A.
Explanation: Slope in returns space measures sensitivity (beta-like co-movement).
Q43. For robust correlation under outliers:
A) Pearson
B) Spearman rank
C) Cosine similarity
D) Kendall’s τ is identical to Pearson
Answer: B.
Explanation: Spearman uses ranks and is less sensitive to outliers.
4. Context: Referring to the dataset fields, specifically 'change', which is the difference
between closing prices of two successive days5. If a data scientist needs to quickly verify
this 'change' column using the 'close' price, which pandas operation is the most
appropriate?
A. df['close'].diff()
B. df['close'].shift(1)
C. df['close'].pct_change()
D. df['close'].rolling(2).sum()
Correct Answer: A. df['close'].diff()
Explanation: The .diff() method calculates the difference between the current element and
the preceding element, matching the definition of 'change'.
5. Context: A dataset containing sales transactions is loaded, and the analyst wants to find the
total sales amount. The 'Quantity' column is correctly numeric, but the 'Price' column is
loaded as an object due to a currency symbol (e.g., '$10.00' vs '10.00'). To correctly
calculate the total sales (Quantity x Price), what is the correct sequence of ETL steps?
A. Extract Price $\rightarrow$ Calculate Total Sales $\rightarrow$ Load
B. Extract Price $\rightarrow$ Remove currency symbol $\rightarrow$ Convert to numeric
$\rightarrow$ Calculate Total Sales $\rightarrow$ Load
C. Extract Price $\rightarrow$ Fill missing values $\rightarrow$ Calculate Total Sales
$\rightarrow$ Load
D. Extract Price $\rightarrow$ Convert to datetime $\rightarrow$ Calculate Total Sales
$\rightarrow$ Load
Correct Answer: B. Extract Price $\rightarrow$ Remove currency symbol $\rightarrow$
Convert to numeric $\rightarrow$ Calculate Total Sales $\rightarrow$ Load
Explanation: The currency symbol must be cleaned (removed) before the column can be
transformed (converted) to a numeric type for calculation.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 14
9. Context: An analyst working with the MCB stock data finds a single day's 'close' price that is
ten times the preceding and following day's price—a clear data entry error (an outlier). The
best immediate ETL strategy to address this before further analysis is to:
A. Replace the value with the mean of the entire 'close' price column.
B. Replace the value with NaN and then use linear interpolation.
C. Censor the value by replacing it with the 95th percentile.
D. Winsorize the entire 'close' column.
Correct Answer: B. Replace the value with NaN and then use linear interpolation.
Explanation: Replacing the extreme outlier with NaN and interpolating effectively smooths
the value based on the trend of its neighbors, minimizing distortion while correcting the
error.
12. Context: A new column, 'percentchange', is required in ABL, calculated as the daily
percentage change in closing price compared to the previous day's closing price9. Which
Python code correctly calculates this metric?
A. ABL['percentchange'] = ABL['close'].diff() / ABL['close'].shift(1)
B. ABL['percentchange'] = ABL['close'].diff()
C. ABL['percentchange'] = ABL['close'] / ABL['close'].shift(1) - 1
D. ABL['percentchange'] = ABL['close'].pct_change()
Correct Answer: D. ABL['percentchange'] = ABL['close'].pct_change()
Explanation: The .pct_change() method is the dedicated and most efficient pandas function
for calculating the percentage change over the previous period.
13. Context: The Interquartile Range (IQR) is a robust measure of statistical dispersion. If the
25th percentile (Q1) of ABL's 'open' price is 95.00 and the 75th percentile (Q3) is 108.00,
what is the most appropriate interpretation of the IQR?
A. The stock price has a minimum variability of 13.00.
B. 50% of the daily opening prices fall within a 13.00 range.
C. The average deviation of the opening price is 13.00.
D. The stock price's standard deviation is 13.00.
Correct Answer: B. 50% of the daily opening prices fall within a 13.00 range.
Explanation: The IQR ($Q3 - Q1 = 13.00$) by definition covers the middle 50% of the data
distribution.
14. Context: A Chartered Accountant (CA) is assessing the internal control over asset
valuation, using a dataset of fixed asset costs. The variance of asset costs is computed as
50,000. Why is the standard deviation a more practically useful metric for reporting to the
audit partner?
A. Standard deviation is easier to calculate.
B. Standard deviation is always a larger number than variance.
C. Standard deviation is in the same units as the mean (e.g., currency), making it directly
interpretable.
D. Standard deviation only measures relative dispersion.
Correct Answer: C. Standard deviation is in the same units as the mean (e.g., currency),
making it directly interpretable.
Explanation: Standard deviation is the square root of variance, which restores the measure
of spread to the original data units, providing better business context.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 17
Explanation: Since p-value (0.005) is less than $\alpha$ (0.05), the null hypothesis is
rejected.
18. Context: Which of the following analytical tasks falls under Predictive Analytics in Gartner’s
Model?
A. Calculating the average daily trading volume for UBL stock last quarter12.
B. Identifying why MCB stock price dropped sharply on a specific date (Root Cause
Analysis).
C. Forecasting the MARI stock price for the next 30 days using a time-series model.
D. Recommending the optimal quantity of ABL stock to buy to maximize profit.
Correct Answer: C. Forecasting the MARI stock price for the next 30 days using a time-
series model.
Explanation: Predictive Analytics uses historical data to forecast what will happen in the
future.
19. Context: A model determines the optimal cash reserves a company should hold to minimize
opportunity cost while meeting all expected liabilities. This analysis belongs to which
category of Gartner's Analytics Model?
A. Descriptive Analytics
B. Diagnostic Analytics
C. Predictive Analytics
D. Prescriptive Analytics
Correct Answer: D. Prescriptive Analytics
Explanation: Prescriptive Analytics recommends the best course of action (i.e.,
optimization) to achieve a desired outcome.
21. Context: For MCB, the task involves plotting the 10-day, 20-day, and 30-day moving
averages alongside the actual closing price14. Which pandas function is used to calculate
the simple moving average (SMA) for a time series?
A. MCB['close'].mean()
B. MCB['close'].diff(10)
C. MCB['close'].rolling(window=10).mean()
D. MCB['close'].shift(10)
Correct Answer: C. MCB['close'].rolling(window=10).mean()
Explanation: The .rolling(window=N).mean() method calculates the N-period simple moving
average, the standard technique for smoothing time-series data.
22. Context: A fund manager wants to compare the distribution of daily 'volume' traded across
all four companies (ABL, MARI, MCB, UBL) on a single chart to identify which stock has the
most sporadic trading activity. Which type of plot is best suited for this comparison of
distributions?
A. Scatter Plot
B. Bar Chart
C. Line Plot
D. Box Plot
Correct Answer: D. Box Plot
Explanation: Box plots are excellent for visually comparing the distribution, spread (IQR),
median, and outliers of a single numeric variable across multiple categories.
23. Context: To visualize the computed correlation between the 'close' prices of ABL and
MCB15, which plot type is the most direct and effective?
A. Histogram of ABL 'close' price
B. Bar chart of average 'close' prices
C. Scatter Plot of ABL 'close' vs. MCB 'close'
D. Heatmap of a single column's values
Correct Answer: C. Scatter Plot of ABL 'close' vs. MCB 'close'
Explanation: A scatter plot visually represents the relationship between two variables,
making it the ideal tool to assess the linearity, direction, and strength of correlation.
24. Context: In financial data visualization, Candlestick Charts are common. Candlestick charts
visually encode which four essential daily price points?
A. Open, Close, High, Volume
B. Open, Close, Low, Volume
C. High, Low, Volume, Change
D. Open, Close, High, Low
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 20
C. The notebook provides a self-documenting, cell-by-cell audit trail of the data extraction,
transformation, analysis, and conclusion steps.
D. Jupyter Notebooks can only handle small datasets.
Correct Answer: C. The notebook provides a self-documenting, cell-by-cell audit trail of the
data extraction, transformation, analysis, and conclusion steps.
Explanation: The linear, combined code/narrative format of Jupyter is perfect for audit
documentation, ensuring reproducibility and clear review.
28. Context: An auditor uses Python to analyze a dataset of journal entries. They find a high
volume of entries posted after the fiscal year-end date. This finding primarily supports which
stage of the audit conclusion process?
A. Forming a conclusion on the client's credit risk.
B. Evidence of potential period-end cutoff misstatements.
C. Assessing the validity of the going concern assumption.
D. Verifying the physical existence of assets.
Correct Answer: B. Evidence of potential period-end cutoff misstatements.
Explanation: Transactions recorded after the year-end date often indicate a failure in the
accounting cutoff assertion.
29. Context: Which Numpy operation is most useful for an auditor who needs to create a
summary table that cross-references the counts of transactions by two categorical factors
(e.g., 'Region' and 'Transaction Type')?
A. [Link]()
B. [Link]()
C. pd.pivot_table()
D. [Link]()
Correct Answer: C. pd.pivot_table()
Explanation: The pivot_table function is the most flexible Pandas tool for summarizing
(aggregating counts, sums, means) data across two or more dimensions, forming a cross-
reference table.
30. Context: In performing a substantive test of detail on a large accounts receivable balance,
an auditor uses stratified sampling to ensure high-value accounts are selected. Which
Pandas method facilitates this selection process?
A. [Link](100)
B. [Link](frac=0.1)
C. [Link]('Value_Band').sample(n=10, replace=False)
D. [Link]()
Correct Answer: C. [Link]('Value_Band').sample(n=10, replace=False)
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 22
Explanation: Stratified sampling requires drawing samples from pre-defined groups (strata),
which is achieved efficiently in Pandas using the groupby().sample() chain.
C. [Link]()
D. [Link]()
Correct Answer: C. [Link]()
Explanation: [Link]() computes the running sum of an array, which translates directly
to the cumulative change over time.
34. Context: A data scientist is analyzing the impact of interest rate announcements on all four
stocks. They need to merge the stock datasets (ABL, MARI, MCB, UBL) 20 with an external
'[Link]' file containing a 'Date' column and an 'Announcement_Impact'
column. Which type of pandas merge/join operation is typically used to combine two
datasets based on a common 'Date' column?
A. [Link]()
B. [Link](..., on='date', how='inner')
C. [Link]()
D. [Link]()
Correct Answer: B. [Link](..., on='date', how='inner')
Explanation: [Link]() is the function used to combine DataFrames based on common
key columns, in this case, the 'date'.
35. Context: Which of the following Pandas operations would be the most computationally
expensive on a massive 10-year daily stock price dataset?
A. Calculating the mean 'close' price.
B. Filtering the data for prices greater than 100.
C. Calculating a 200-day Exponential Moving Average (EMA) using the ewm() method.
D. Displaying the first 5 rows (.head()).
Correct Answer: C. Calculating a 200-day Exponential Moving Average (EMA) using the
ewm() method.
Explanation: EMA is computationally intensive because it's a recursive calculation where
each day's value depends on the previous day's EMA, requiring processing of all prior data
points.
D. [Link](ABL['close'])
Correct Answer: B. ABL['close'].to_numpy()
Explanation: .to_numpy() is the modern and preferred method in Pandas to efficiently
extract the underlying data as a NumPy array.
37. A Fund Manager needs to simulate a Monte Carlo analysis for UBL stock returns. Which
fundamental NumPy module is required to generate a large number of random samples
from a specified probability distribution?
A. [Link]
B. [Link]
C. [Link]
D. [Link]
Correct Answer: B. [Link]
Explanation: The [Link] module provides the core functions for generating random
numbers and samples from various statistical distributions, essential for simulations.
38. If arr = [Link]([1, 2, 3, 4, 5]) is the 'close' price of MCB for 5 days, and the analyst runs
arr[arr > 3], what NumPy concept is being demonstrated?
A. Array concatenation
B. Boolean Indexing
C. Slicing
D. Vector product
Correct Answer: B. Boolean Indexing
Explanation: Boolean Indexing uses a True/False array (generated by the condition $arr >
3$) to select elements from the original array where the condition is True.
Explanation: A Kernel Density Estimate (KDE) plot visualizes the probability density
function, making it ideal for comparing the spread and shape of two distributions (volatility).
40. An analyst creates a Heatmap of the correlation matrix for all four stocks (ABL, MARI, MCB,
UBL). If the color scale ranges from dark blue (-1) to dark red (+1), what does a white or
light gray square in the center of the heatmap signify?
A. Perfect positive correlation (+1).
B. Perfect negative correlation (-1).
C. Zero or very low linear correlation (~ 0).
D. Missing data (NaN).
Correct Answer: C. Zero or very low linear correlation (~ 0).
Explanation: In a diverging color scale used for correlation, the neutral or lightest color
typically represents the midpoint, which is a correlation value of 0.
41. A Pair Plot (or Scatterplot Matrix) is generated for the 'open', 'high', 'low', and 'close' prices
of the UBL stock21. What does the Pair Plot display on its diagonal cells by default?
A. A single scatter plot of 'high' vs. 'low'.
B. The correlation coefficient for the two adjacent variables.
C. Univariate distributions (usually Histograms or KDEs) for each variable.
D. A time-series line plot.
Correct Answer: C. Univariate distributions (usually Histograms or KDEs) for each variable.
Explanation: The diagonal of a Pair Plot shows the relationship of a variable with itself,
which is best represented by its distribution (histogram or KDE).
43. An auditor wants to identify all vendors in the 'Vendor_Payments' dataset who have an
'Invoice_Date' before the 'Service_Rendered_Date', which is an impossible sequence
indicating a data integrity issue. Which Pandas technique is the most efficient way to
generate the list of unique vendors involved in these exceptions?
A. df[df['Invoice_Date'] < df['Service_Rendered_Date']]['Vendor_ID'].value_counts()
B. df.pivot_table(index='Vendor_ID', values='Amount', aggfunc='mean')
C. [Link](other_df, on='Vendor_ID')
D. [Link]()
Correct Answer: A. df[df['Invoice_Date'] <
df['Service_Rendered_Date']]['Vendor_ID'].value_counts()
Explanation: This uses boolean indexing to filter for the impossible exceptions and then
counts the frequency of the 'Vendor_ID' in the resulting subset.
44. A CA uses Python to perform Benford's Law analysis on inventory quantities. Benford's Law
tests the expected frequency distribution of the first digit in naturally occurring numbers. If a
significant deviation is detected (a high $\chi^2$ test statistic), this is strong evidence of:
A. The data being normally distributed.
B. The inventory quantities being very high.
C. Potential manipulation or fabrication of the numbers.
D. The numbers following a Uniform distribution.
Correct Answer: C. Potential manipulation or fabrication of the numbers.
Explanation: Benford's Law is a primary forensic tool; significant deviation suggests the
numbers were not naturally generated (e.g., they were manually entered or altered).
45. In a real-world scenario, an auditor is tasked with assessing the Going Concern
assumption. Which analytical task, using Python, would provide the strongest quantitative
evidence for this assessment?
A. Calculating the average office supply expense.
B. Performing time-series forecasting on the company's working capital for the next 12
months.
C. Plotting a histogram of the sales staff's commission rates.
D. Computing the correlation between sales and marketing spend.
Correct Answer: B. Performing time-series forecasting on the company's working capital for
the next 12 months.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 27
Explanation: Forecasting financial viability (cash flow or working capital) is central to the
Going Concern assessment.
46. Which of the following is an example of an audit use case for Predictive Analytics?
A. Using an SQL query to list all outstanding invoices over 90 days.
B. Identifying the GL account with the highest mean balance last year.
C. Training a machine learning model to predict the likelihood of a customer default (bad
debt) to inform the allowance for doubtful accounts.
D. Plotting a bar chart of the top 10 vendors by payment volume.
Correct Answer: C. Training a machine learning model to predict the likelihood of a
customer default (bad debt) to inform the allowance for doubtful accounts.
Explanation: Predicting future outcomes (like default probability) is the core function of
Predictive Analytics.
47. A large Pandas DataFrame of UBL stock data is created. To conserve memory and speed
up subsequent analysis, a Fund Manager decides to drop all columns except 'date' and
'close'. Which of the following Pandas methods is the correct and most efficient way to
achieve this?
A. [Link](columns=['open', 'high', 'low', 'volume', 'change'], inplace=True)
B. UBL[['date', 'close']]
C. [Link]()
D. [Link]()
Correct Answer: A. [Link](columns=['open', 'high', 'low', 'volume', 'change'],
inplace=True)
Explanation: Using .drop() with inplace=True modifies the existing DataFrame in memory by
removing specified columns, which is an efficient cleaning technique.
48. A Seaborn Violin Plot is created for the daily ABL returns. How does it enhance the
visualization of the data distribution compared to a simple Box Plot?
A. It only shows the median and quartiles.
B. It displays a regression line for the data.
C. It shows the full kernel density estimate (KDE) of the distribution, not just the summary
statistics.
D. It plots all the individual data points as a swarmplot.
Correct Answer: C. It shows the full kernel density estimate (KDE) of the distribution, not
just the summary statistics.
Instructor: Syed Ali Ameer 100 Practice MCQs – Python Programming 28
Explanation: The Violin Plot's shape represents the KDE, revealing the density, modality,
and shape of the data distribution, unlike the box plot which is limited to quartiles.
49. Context: The MCB moving average task is part of technical analysis22. The primary reason
for plotting both the 10-day (short-term) and 30-day (long-term) moving averages is to:
A. Calculate the stock's RSI.
B. Identify the "golden cross" or "death cross" signals by observing when the short-term
average crosses the long-term average.
C. Determine the P/E ratio.
D. Forecast the daily closing price with high accuracy.
Correct Answer: B. Identify the "golden cross" or "death cross" signals by observing when
the short-term average crosses the long-term average.
Explanation: The crossing of different period SMAs (e.g., a short-term moving average
crossing above a long-term one) is a key trend change signal in technical analysis.
50. NumPy's broadcasting feature is a key reason for Python's speed in data analytics. If a
Fund Manager calculates the Excess Return for all stocks by subtracting a Risk-Free Rate
(e.g., 0.0001) from every element of the 'percentchange' column, this is an example of:
A. Matrix multiplication
B. Broadcasting
C. Array stacking
D. NumPy Looping
Correct Answer: B. Broadcasting
Explanation: Broadcasting is the NumPy mechanism that allows arithmetic operations
between arrays of different shapes (like a 1D array of returns and a single scalar
value/float) by implicitly extending the scalar to match the array's shape.
The method `UBL['date'].is_monotonic_increasing` can be used to efficiently check if a date column is strictly increasing in a Pandas DataFrame. This method directly verifies the monotonicity of the date sequence .
The `sns.boxplot()` method from Seaborn is ideal for visualizing the distribution of numeric data along with potential outliers. It graphically depicts the interquartile range and highlights values that fall outside this range .
Merging on date is the best technique to ensure data alignment when calculating correlations between closing prices in two DataFrames. This alignment is necessary to correlate data that corresponds to the same trading dates .
Jupyter Notebooks provide a self-documenting, cell-by-cell audit trail, combining narrative and code. This format ensures reproducibility and clear documentation for audits, making it advantageous compared to standard Python scripts .
To verify the data type of a specific column in a Pandas DataFrame, access the column's `.dtype` attribute. For example, using `ABL['volume'].dtype` provides a direct and unambiguous method to check the data type of the column .
The method `MARI['close'].rolling(5).median()` can be used to efficiently compute the rolling 5-day median of a column. This method automatically skips NaN values, making it ideal for datasets containing missing data .
To calculate a 200-day EMA on a large dataset, you would use the `ewm()` method with a span of 200. This method computes the moving average using weights that decrease exponentially, allowing EMA to capture more recent price changes effectively .
To ensure schema consistency before concatenating multiple DataFrames, you should reindex all frames to a standard column list. This ensures that the columns are aligned in both order and naming .
Maintaining deterministic transforms along with versioned code and data lineage is most crucial for auditability in ETL processes. These factors ensure that the process is reproducible and all transformations can be traced for audits .
The method `pd.to_numeric(..., errors='coerce')` is the most robust option for converting data to numeric types while ensuring non-parsable entries are set to NaN. This approach is necessary before performing operations like imputation .