Data Science with Python Certification — Questions and Answers
Question 1: After one-hot encoding a categorical column with 5 unique values, how many new columns are created to avoid the dummy variable trap?
- 4 (Correct answer)
- 6
- 3
- 5
Correct answer: 4
Dropping one category (drop_first=True) leaves 4 columns, preventing perfect multicollinearity.
Question 2: What does the `zip()` function return when passed two lists of unequal length?
- Stops at the length of the shorter list (Correct answer)
- Stops at the length of the longer list
- Pads the shorter list with None
- Raises a ValueError
Correct answer: Stops at the length of the shorter list
`zip()` stops producing tuples when the shortest input iterable is exhausted.
Question 3: In DBSCAN, what is a 'border point'?
- A point that defines cluster boundaries algorithmically
- A point with no neighbors within epsilon
- A point within epsilon of a core point but not itself a core point (Correct answer)
- A core point on the edge of the dataset
Correct answer: A point within epsilon of a core point but not itself a core point
A border point is reachable from a core point but has fewer than MinPts neighbors within epsilon.
Question 4: In pandas, what does df.duplicated().sum() compute?
- The number of columns with duplicate names
- The index of the first duplicated row
- The total number of duplicate rows in the DataFrame (Correct answer)
- The sum of all duplicated values across columns
Correct answer: The total number of duplicate rows in the DataFrame
df.duplicated() returns a boolean Series marking duplicate rows, and .sum() counts how many are True.
Question 5: You are given two 1D NumPy arrays, `a1 = np.array([1, 2, 3])` and `a2 = np.array([4, 5, 6])`. Which function would you use to combine them into a single 2D array where `a1` is the first row and `a2` is the second row?
- np.concatenate((a1, a2), axis=1)
- np.vstack((a1, a2)) (Correct answer)
- np.hstack((a1, a2))
- np.column_stack((a1, a2))
Correct answer: np.vstack((a1, a2))
`np.vstack()` stacks arrays in sequence vertically (row-wise). It takes a tuple of arrays as input and stacks them one on top of the other, creating a new dimension. `hstack` would append them horizontally, and `concatenate` with `axis=1` would raise an error for 1D arrays.
Question 6: What is the result of `np.arange(10).reshape(2,5)[1, ::2]`?
- array([5, 7, 9]) (Correct answer)
- array([5, 6, 7, 8, 9])
- array([1, 3])
- array([6, 8])
Correct answer: array([5, 7, 9])
Row index 1 gives [5,6,7,8,9], and step-2 slicing starting at 0 yields elements at positions 0,2,4 → [5,7,9].
Question 7: When using GridSearchCV in scikit-learn, what does the refit=True parameter do?
- Runs cross-validation twice
- Refits the model on each fold separately
- Saves all fitted models to disk
- Refits the best estimator on the entire training set after search (Correct answer)
Correct answer: Refits the best estimator on the entire training set after search
refit=True causes GridSearchCV to retrain the best-found model on the complete training data, making it ready for prediction.
Question 8: In a Support Vector Machine (SVM) model, what is the primary purpose of the 'kernel trick'?
- To efficiently compute dot products in a high-dimensional feature space without explicitly mapping the data, allowing the model to find non-linear decision boundaries. (Correct answer)
- To reduce the number of features in the dataset before training the model.
- To select the most important support vectors that define the margin.
- To transform the data into a lower-dimensional space to make it linearly separable.
Correct answer: To efficiently compute dot products in a high-dimensional feature space without explicitly mapping the data, allowing the model to find non-linear decision boundaries.
The kernel trick is a core concept in SVMs that allows them to solve non-linear classification problems. It works by implicitly mapping the input data into a higher-dimensional space where a linear separator can be found. The 'trick' is that it achieves this without ever having to compute the coordinates of the data in that high-dimensional space, instead calculating the dot products directly in the original space, which is computationally efficient.
Question 9: When applying PCA, what does a negative eigenvalue indicate?
- A direction of maximum compression
- A principal component that explains negative variance
- A numerical error, since covariance matrices always yield non-negative eigenvalues (Correct answer)
- An outlier principal component
Correct answer: A numerical error, since covariance matrices always yield non-negative eigenvalues
Covariance matrices are positive semi-definite, so all eigenvalues must be ≥ 0; negatives indicate numerical precision errors.
Question 10: Which pandas method creates a rolling window calculation on a time series?
- df.rolling() (Correct answer)
- df.shift()
- df.diff()
- df.cumsum()
Correct answer: df.rolling()
`df.rolling(window)` creates a rolling window object enabling moving averages and other window-based aggregations.
Question 11: What is the result of df.duplicated() on a DataFrame?
- Returns only duplicate rows
- Returns a boolean Series marking duplicate rows (Correct answer)
- Counts duplicates per column
- Drops all duplicate rows
Correct answer: Returns a boolean Series marking duplicate rows
df.duplicated() returns a boolean Series where True indicates a row is a duplicate of a previous row.
Question 12: You are tasked with visualizing the relationship between two continuous variables, 'total_bill' and 'tip', from a dataset. Additionally, you want to see the distribution of each of these variables individually along the axes of the same plot. Which Seaborn function is best suited for this purpose?
- sns.jointplot() (Correct answer)
- sns.boxplot()
- sns.pairplot()
- sns.scatterplot()
Correct answer: sns.jointplot()
`sns.jointplot()` is specifically designed to solve this problem. It creates a scatter plot to show the bivariate relationship between two variables and adds histograms or KDE plots for each variable in the margins, showing their individual distributions.
Question 13: Which Python function from sklearn.metrics computes the confusion matrix for a classification model?
- sklearn.metrics.accuracy_score()
- sklearn.metrics.roc_auc_score()
- sklearn.metrics.confusion_matrix() (Correct answer)
- sklearn.metrics.classification_report()
Correct answer: sklearn.metrics.confusion_matrix()
sklearn.metrics.confusion_matrix(y_true, y_pred) returns the matrix of true vs. predicted class counts.
Question 14: What is the primary purpose of using k-fold cross-validation in machine learning?
- To provide a more robust and stable estimate of a model's performance on unseen data. (Correct answer)
- To increase the speed of model training on large datasets.
- To completely eliminate the need for a final, held-out test set.
- To automatically select the best features for the model.
Correct answer: To provide a more robust and stable estimate of a model's performance on unseen data.
K-fold cross-validation involves repeatedly training and testing a model on different subsets ('folds') of the data. By averaging the performance scores from each fold, it provides a more reliable and less biased estimate of how the model will generalize to new, independent data compared to a single train-test split.
Question 15: A data analyst is working with a DataFrame `market_data` and needs to create a new column called 'ProfitMargin'. This column should be calculated as `(market_data['Revenue'] - market_data['Cost']) / market_data['Revenue']`. Which of the following is the most idiomatic Pandas way to add this new column?
- for index, row in market_data.iterrows(): market_data.loc[index, 'ProfitMargin'] = (row['Revenue'] - row['Cost']) / row['Revenue']
- market_data.insert(column='ProfitMargin', value=(market_data.Revenue - market_data.Cost) / market_data.Revenue)
- market_data.apply(lambda row: (row['Revenue'] - row['Cost']) / row['Revenue'], axis=1)
- market_data['ProfitMargin'] = (market_data['Revenue'] - market_data['Cost']) / market_data['Revenue'] (Correct answer)
Correct answer: market_data['ProfitMargin'] = (market_data['Revenue'] - market_data['Cost']) / market_data['Revenue']
Pandas supports vectorized operations, which are highly efficient. Directly performing arithmetic operations on columns (which are Pandas Series) is the most direct and performant way to create a new column based on existing ones. Using `.apply()` or iterating with `iterrows()` is much less efficient for this type of calculation.
Question 16: Which of the following statements best describes a primary advantage of using Seaborn over Matplotlib?
- Seaborn is required for creating basic plots like line charts and bar charts.
- Seaborn provides more low-level control over every individual plot element.
- Seaborn offers faster rendering performance for simple visualizations.
- Seaborn is a high-level interface that creates visually appealing statistical plots with less code. (Correct answer)
Correct answer: Seaborn is a high-level interface that creates visually appealing statistical plots with less code.
Seaborn is built on top of Matplotlib and provides a higher-level API. Its main advantages are its ability to create complex and aesthetically pleasing statistical plots with more concise syntax, its beautiful default styles, and its seamless integration with Pandas DataFrames.
Question 17: How do you parse a date column automatically when reading a CSV file with pandas?
- pd.read_csv(file, parse_dates=['date']) (Correct answer)
- pd.read_csv(file, date_col='date')
- pd.read_csv(file, index_dates=['date'])
- pd.read_csv(file, datetime='date')
Correct answer: pd.read_csv(file, parse_dates=['date'])
The `parse_dates` parameter in `pd.read_csv()` automatically converts specified columns to pandas datetime objects.
Question 18: Which Matplotlib function creates a figure with multiple subplots and returns both the figure and axes objects?
- plt.figure()
- plt.subplots() (Correct answer)
- plt.axes()
- plt.subplot()
Correct answer: plt.subplots()
plt.subplots() creates a figure and a grid of subplots, returning (fig, axes) as a tuple.
Question 19: What is the interquartile range (IQR) commonly used for in data science?
- Identifying the most frequent value
- Computing the correlation coefficient
- Measuring the average of the dataset
- Measuring the spread of the middle 50% of data (Correct answer)
Correct answer: Measuring the spread of the middle 50% of data
IQR is the difference between Q3 and Q1, capturing the spread of the central 50% of data and is used for outlier detection.
Question 20: In Matplotlib, which method saves the current figure to a file?
- plt.store()
- plt.write()
- plt.export()
- plt.savefig() (Correct answer)
Correct answer: plt.savefig()
plt.savefig('filename.png') saves the current figure to disk in the specified format.
Question 21: What does a scikit-learn linear model that estimates sparse coefficients look like?
- Lasso (Correct answer)
- None of these
- LinearRegression
- Ridge Regression
Correct answer: Lasso
Explanation: <br> In scikit-learn, a linear model that estimates sparse coefficients is called Lasso. Lasso stands for "Least Absolute Shrinkage and Selection Operator." It is a linear regression model that performs both regularization and feature selection.
Question 22: You are analyzing a correlation heatmap generated using Seaborn to understand the relationships between numerical features in a dataset. What does a cell with a bright, dark red color and an annotation of `0.85` typically signify (using a standard 'coolwarm' or similar diverging colormap)?
- A perfect negative correlation between the two variables.
- A strong positive correlation between the two variables. (Correct answer)
- A weak negative correlation between the two variables.
- No correlation between the two variables.
Correct answer: A strong positive correlation between the two variables.
In a standard diverging colormap like 'coolwarm' used for correlation heatmaps, warm colors (like red) represent positive correlations, while cool colors (like blue) represent negative correlations. [18] The intensity of the color indicates the strength of the correlation, and the annotated value provides the precise coefficient. A value of 0.85 is close to +1, indicating a strong positive correlation. [6, 18]
Question 23: Which NumPy function stacks arrays vertically (row-wise)?
- np.column_stack
- np.vstack (Correct answer)
- np.concatenate(axis=1)
- np.hstack
Correct answer: np.vstack
np.vstack stacks a sequence of arrays along the first (vertical) axis, equivalent to concatenate with axis=0.
Question 24: What command will enable you to obtain a stack trace while using the interactive Python debugger?
- Where (Correct answer)
- Step
- P
- Whatis
Correct answer: Where
Explanation: <br> The command at the interactive Python debugger prompt that helps you in getting a stack trace while debugging a Python program is where or w.
Question 25: When using pandas, what does df.groupby('category')['value'].agg(['mean','std']) return?
- A list of tuples with group keys and aggregates
- A single scalar value
- A DataFrame with mean and std for each category group (Correct answer)
- A Series indexed by column names
Correct answer: A DataFrame with mean and std for each category group
agg() with a list of functions returns a DataFrame where each row is a group and each column is an aggregated statistic.
Question 26: The character used to indicate end of a block in Python, is
- Nothing (Correct answer)
- :
- ;
- /
Correct answer: Nothing
Explanation: <br> In Python, the character used to indicate the end of a block is not a specific character like in some other programming languages. Instead, Python uses indentation to define the blocks of code.
Question 27: What will `'data'[::-1]` return in Python?
- Raises IndexError
- 'atad' (Correct answer)
- 'data'
- 'dta'
Correct answer: 'atad'
The slice `[::-1]` reverses a string by stepping backwards through all characters.
Question 28: Which method converts a pandas Series of strings to datetime objects?
- pd.to_datetime(Series) (Correct answer)
- Series.cast(dtype='datetime')
- Series.astype('datetime64')
- Series.datetime.parse()
Correct answer: pd.to_datetime(Series)
pd.to_datetime() is the standard function for parsing strings or numbers into datetime objects.
Question 29: An unconstrained Decision Tree is trained on a complex dataset and achieves 100% accuracy on the training data but performs poorly on the test data. What is this phenomenon called, and what is a common way to mitigate it in Scikit-learn?
- Overfitting; set the `max_depth` parameter to a smaller integer. (Correct answer)
- Underfitting; decrease the `min_samples_leaf` parameter.
- Bias-Variance Tradeoff; increase the number of features.
- Curse of Dimensionality; use a more complex model.
Correct answer: Overfitting; set the `max_depth` parameter to a smaller integer.
This scenario describes overfitting, where the model learns the training data too well, including its noise, and fails to generalize to new data. Decision trees are prone to overfitting if not constrained. A common mitigation strategy is to prune the tree by limiting its maximum depth using the `max_depth` hyperparameter in Scikit-learn, which prevents it from becoming overly complex.
Question 30: What is the primary purpose of removing stop words in NLP preprocessing?
- To convert words to their base grammatical form
- To split sentences into individual characters
- To correct spelling errors in the text
- To reduce vocabulary size and eliminate low-information words (Correct answer)
Correct answer: To reduce vocabulary size and eliminate low-information words
Stop words like 'the', 'is', and 'and' carry little semantic meaning; removing them reduces noise and shrinks the feature space.
Question 31: Beyond the formal parameter list in Python, the variadic arguments are contained in
- Tree (Correct answer)
- Dictionary
- Tuple (Correct answer)
- Stack
Correct answer: Tree
When a function uses *args, Python packs the extra positional arguments into a TUPLE — an immutable ordered collection. It is not a stack, dictionary, or tree. ⚠ The stored key ('Tree') is wrong, and the correct value 'tuple' is not among the options, so this question should be rewritten.
Question 32: Which statistical test should you use to compare means across more than two groups?
- ANOVA (Correct answer)
- Chi-square test
- t-test
- z-test
Correct answer: ANOVA
ANOVA (Analysis of Variance) tests for differences in means across three or more independent groups.
Question 33: What does `np.broadcast_to(a, shape)` do?
- Raises an error if shapes are incompatible
- Copies array data to match the new shape
- Returns a read-only view of the array broadcast to the given shape (Correct answer)
- Creates a writable array with the broadcast shape
Correct answer: Returns a read-only view of the array broadcast to the given shape
`np.broadcast_to` returns a read-only view of the array stretched to the target shape without copying data.
Question 34: Given a Pandas DataFrame named `sales`, which of the following code snippets correctly calculates the total sales for each 'Region' by summing the 'Sales' column?
- sales.sum('Sales').by('Region')
- sales.pivot(index='Region', values='Sales', aggfunc='sum')
- sales.aggregate('Sales').on('Region')
- sales.groupby('Region')['Sales'].sum() (Correct answer)
Correct answer: sales.groupby('Region')['Sales'].sum()
The `groupby()` method is used to split the DataFrame into groups based on some criteria, in this case, the 'Region' column. Then, `['Sales']` selects the 'Sales' column from each group, and `.sum()` is an aggregation function that calculates the sum of the 'Sales' for each region.
Question 35: Which attribute gives the total number of elements in a NumPy array?
- array.size (Correct answer)
- array.itemsize
- array.ndim
- array.shape
Correct answer: array.size
`array.size` returns the total count of elements (product of all shape dimensions).
Question 36: What is the primary risk of applying target encoding before performing cross-validation?
- Loss of categorical information
- Increased training time
- Multicollinearity in features
- Data leakage from the target variable (Correct answer)
Correct answer: Data leakage from the target variable
Applying target encoding before cross-validation leaks target information into the training folds, causing overly optimistic model evaluation.
Question 37: Which of the following scenarios is the primary reason for converting a column's data type from `object` to a more specific type like `int` or `float` during data cleaning?
- To ensure all columns have the same number of unique values.
- To enable mathematical operations and improve memory efficiency. (Correct answer)
- To prepare the data for export to a JSON file, which requires numeric types.
- To make the DataFrame display more aesthetically pleasing.
Correct answer: To enable mathematical operations and improve memory efficiency.
Columns with an `object` dtype often store strings, which prevents numerical calculations. Converting them to `int` or `float` using methods like `astype()` or `pd.to_numeric()` is essential for performing mathematical and statistical operations. Additionally, numeric types are generally more memory-efficient than object types.
Question 38: What plot evaluates the unpredictability of time series?
- Autocorrelation (Correct answer)
- Autocausation
- None of these
- Autorank
Correct answer: Autocorrelation
Explanation: <br> An autocorrelation plot is a plot that helps check randomness in a time series. It is commonly used to identify patterns or dependencies in the data over different lags (time intervals).
Question 39: Which seaborn plot is best for visualizing the relationship between two continuous variables along with their marginal distributions?
- sns.heatmap()
- sns.violinplot()
- sns.jointplot() (Correct answer)
- sns.stripplot()
Correct answer: sns.jointplot()
sns.jointplot() shows a scatter plot of two variables plus their individual marginal histograms or KDEs.
Question 40: In pandas, what does the method df.dropna() do by default?
- Fills missing values with zero
- Removes duplicate rows
- Drops columns with any missing values
- Drops rows with any missing values (Correct answer)
Correct answer: Drops rows with any missing values
By default, df.dropna() removes any row that contains at least one NaN value (axis=0).
Question 41: Which of the following methods would you use to remove duplicate rows from a DataFrame `df` based on the values in the 'email' column, keeping the first occurrence?
- df.remove(duplicates=True, column='email')
- df.unique(subset=['email'])
- df.delete_duplicates(on='email')
- df.drop_duplicates(subset=['email'], keep='first') (Correct answer)
Correct answer: df.drop_duplicates(subset=['email'], keep='first')
The `drop_duplicates()` method is the correct function for removing duplicate rows. The `subset` parameter allows you to specify which columns to consider for identifying duplicates, and `keep='first'` ensures that the first observed instance of a duplicated row is retained.
Question 42: You have a column with values ['1,200', '3,400', '500']. Which approach correctly converts these to integers?
- df['col'].astype(int)
- pd.to_numeric(df['col'])
- df['col'].int()
- df['col'].str.replace(',', '').astype(int) (Correct answer)
Correct answer: df['col'].str.replace(',', '').astype(int)
You must strip the comma string characters before casting to int since commas are not valid numeric characters.
Question 43: To import Pandas, select the appropriate statement.
- Import pandaspy as pd
- Import pandas as pd (Correct answer)
- All of these
- Import panda as py
Correct answer: Import pandas as pd
Explanation: <br> The statement "import pandas as pd" is a valid way to import the Pandas library in Python. It is a common convention to import Pandas using the alias "pd" to make it easier to refer to the library when using its functions and classes throughout the code.
Question 44: After generating a scatter plot with Matplotlib, you need to add a descriptive title to the plot and label the x-axis and y-axis. Which of the following code snippets correctly accomplishes this?
- plot.title('My Title'); plot.xlabel('X-Axis'); plot.ylabel('Y-Axis')
- plt.figure(title='My Title', xlabel='X-Axis', ylabel='Y-Axis')
- plt.set_title('My Title'); plt.set_xlabel('X-Axis'); plt.set_ylabel('Y-Axis')
- plt.title('My Title'); plt.xlabel('X-Axis'); plt.ylabel('Y-Axis') (Correct answer)
Correct answer: plt.title('My Title'); plt.xlabel('X-Axis'); plt.ylabel('Y-Axis')
The correct functions in Matplotlib's pyplot interface for adding a title, x-label, and y-label are `plt.title()`, `plt.xlabel()`, and `plt.ylabel()`, respectively. Each function takes a string argument to set the corresponding text on the plot.
Question 45: Which Python function performs a one-sample t-test?
- scipy.stats.ttest_1samp() (Correct answer)
- scipy.stats.ttest_ind()
- scipy.stats.f_oneway()
- scipy.stats.ttest_rel()
Correct answer: scipy.stats.ttest_1samp()
`scipy.stats.ttest_1samp()` tests whether the mean of a single sample differs significantly from a specified population mean.
Question 46: What kind of data can be used with Pandas?
- An ndarray
- A python dict
- All of these (Correct answer)
- A scalar value
Correct answer: All of these
Explanation: <br> All of these can be used as data in Pandas. <br> <br> Pandas provide various data structures, such as Series and DataFrame, that can hold and manipulate data. These data structures can be initialized with different types of data.
Question 47: In a dataset for predicting house prices, you have features for 'num_bedrooms' and 'num_bathrooms'. Your initial model is underperforming, and you suspect the combined effect of these two features is more important than their individual effects. Which feature engineering technique would best capture this combined effect?
- Creating an interaction feature, for example, by multiplying 'num_bedrooms' by 'num_bathrooms'. (Correct answer)
- Creating polynomial features for each variable independently (e.g., bedrooms squared).
- Applying standardization to both features to put them on the same scale.
- Binning each feature into categories like 'low', 'medium', and 'high'.
Correct answer: Creating an interaction feature, for example, by multiplying 'num_bedrooms' by 'num_bathrooms'.
Creating an interaction feature by multiplying 'num_bedrooms' and 'num_bathrooms' allows the model to learn the combined effect of these variables. This new feature can capture relationships that the individual features alone cannot, such as a house with many bedrooms AND many bathrooms being disproportionately more valuable. [3, 4, 17]
Question 48: What does a ROC AUC score of 0.5 indicate about a binary classifier?
- Better than random chance
- Performance equivalent to random guessing (Correct answer)
- Perfect classification
- Complete misclassification
Correct answer: Performance equivalent to random guessing
An AUC of 0.5 means the model has no discriminative ability and performs no better than a random classifier.
Question 49: A Support Vector Machine with an RBF kernel has a high value of gamma. What effect does this have?
- Each training point influences a wide region
- Regularization strength increases
- The model underfits with a very smooth decision boundary
- The model overfits with a complex, tightly fitted boundary (Correct answer)
Correct answer: The model overfits with a complex, tightly fitted boundary
High gamma means each training point has a small radius of influence, causing the model to fit training data very tightly and potentially overfit.
Question 50: In a normal distribution, approximately what percentage of data falls within one standard deviation of the mean?
- 99.7%
- 68% (Correct answer)
- 50%
- 95%
Correct answer: 68%
In a normal distribution approximately 68% of data falls within ±1 standard deviation of the mean per the empirical rule.
Question 51: A data analyst has created a line plot using Matplotlib's `plt.plot()` but finds that the plot is not displayed when the script is run. Which of the following functions must be called to render and display the plot?
- plt.display()
- plt.render()
- plt.draw()
- plt.show() (Correct answer)
Correct answer: plt.show()
In Matplotlib, after creating a plot using functions like `plt.plot()`, you must explicitly call `plt.show()` to display the figure. While some environments like Jupyter notebooks might display plots automatically, `plt.show()` is the standard and required function for rendering the plot in most scripts.
Question 52: Choosing the incorrect command to create and reshape a 60-integer array when the NumPy package has been imported as an object with the name np
- myArray=np.arrange(60).reshape(8,7) (Correct answer)
- myArray=np.arrange(60).reshape(12,5)
- myarray=np.linspace(0,60,60).reshape(3,20)
- myArray=np.arrange(60).reshape(10,6)
Correct answer: myArray=np.arrange(60).reshape(8,7)
Explanation: <br> The command myArray = np.arrange(60).reshape(8,7) is not a valid command for creating and reshaping a 60-integer array using NumPy.
Question 53: A data scientist is working on a binary classification problem to predict customer churn. The dataset is highly imbalanced. After training a Random Forest and a Gradient Boosting model, they find that the Gradient Boosting model has higher accuracy. Which of the following is the most likely reason for this outcome?
- Random Forest builds trees in parallel, which is less effective on imbalanced data than the sequential approach of Gradient Boosting.
- Gradient Boosting builds trees sequentially, with each tree focusing on correcting the errors of the previous one, which can be particularly effective for the minority class. (Correct answer)
- Random Forest is inherently a regression algorithm and is less suited for classification tasks.
- Gradient Boosting is less prone to overfitting than Random Forest, especially on noisy datasets.
Correct answer: Gradient Boosting builds trees sequentially, with each tree focusing on correcting the errors of the previous one, which can be particularly effective for the minority class.
Gradient Boosting is often more effective on imbalanced datasets because it builds trees sequentially. Each new tree is built to correct the residual errors of the previous ensemble, which means it can progressively focus more on the hard-to-classify instances, which are often the minority class. Random Forest builds trees independently and in parallel, which may not give specific attention to the underrepresented class.
Question 54: What does a Bonferroni correction adjust for when performing multiple hypothesis tests?
- Sample size bias
- Variance inflation
- Increased Type I error rate (Correct answer)
- Skewness in data
Correct answer: Increased Type I error rate
Bonferroni correction divides the significance threshold by the number of tests to control the family-wise Type I error rate.
Question 55: In t-SNE, what does the perplexity parameter control?
- The number of output dimensions
- The effective number of neighbors considered for each point (Correct answer)
- The random seed for initialization
- The learning rate of gradient descent
Correct answer: The effective number of neighbors considered for each point
Perplexity in t-SNE balances attention between local and global structure by controlling the effective neighborhood size.
Question 56: You are cleaning a dataset of customer information in a pandas DataFrame named 'df'. The 'phone_number' column contains numbers in various formats (e.g., '(123) 456-7890', '123.456.7890', '1234567890'). Which of the following is the most effective approach to standardize all phone numbers to the format '1234567890'?
- Using the `fillna()` method to replace malformed numbers with a standard one.
- Applying the `astype(int)` method to the column.
- Using a for loop to iterate over each phone number and manually replace characters.
- Using the `.str.replace()` method with a regular expression to remove all non-digit characters. (Correct answer)
Correct answer: Using the `.str.replace()` method with a regular expression to remove all non-digit characters.
The `.str.replace()` method in pandas is designed for vectorized string operations and, when combined with a regular expression like `r'\D'`, it can efficiently remove all non-digit characters from the entire column at once. This is more efficient and idiomatic than looping and more flexible than `astype()` which would fail on non-numeric characters. `fillna()` is for handling missing values, not for reformatting existing ones.
Question 57: While cleaning a pandas DataFrame, you discover that a column 'start_date', which should contain dates, is currently of the `object` dtype. Which pandas function is specifically designed to convert such a column to a proper datetime format?
- df['start_date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))
- pd.to_numeric(df['start_date'])
- df['start_date'].astype('datetime64[ns]')
- pd.to_datetime(df['start_date']) (Correct answer)
Correct answer: pd.to_datetime(df['start_date'])
The `pd.to_datetime()` function is the most robust and recommended method for converting an array-like object of strings or other date representations into a pandas DatetimeIndex or Series. It can intelligently parse many different date formats. While `astype('datetime64[ns]')` can work, `to_datetime` is more flexible and powerful, especially with mixed formats or errors. `to_numeric` is for converting to numbers, not dates.
Question 58: What is the primary objective of the Principal Component Analysis (PCA) algorithm?
- To group similar data points into a specified number of clusters.
- To predict a continuous target variable based on one or more predictor variables.
- To reduce the dimensionality of a dataset while preserving the maximum amount of variance. (Correct answer)
- To find the optimal set of hyperparameters for a machine learning model.
Correct answer: To reduce the dimensionality of a dataset while preserving the maximum amount of variance.
Principal Component Analysis (PCA) is a dimensionality reduction technique used to transform a large set of variables into a smaller one that still contains most of the information. [11] It achieves this by identifying a new set of uncorrelated variables, called principal components, that are ordered by the amount of variance they explain in the original data. [23, 5]
Question 59: What is the primary risk of using forward fill (ffill) to impute time-series data?
- It introduces future data leakage
- It removes timezone information
- It converts floats to integers
- It propagates stale values across genuinely missing periods (Correct answer)
Correct answer: It propagates stale values across genuinely missing periods
ffill carries the last valid observation forward, which can mask real gaps and bias analysis if the gap is long.
Question 60: Which Python library provides the `word_tokenize()` function for splitting text into individual tokens?
- TextBlob
- NLTK (Correct answer)
- Gensim
- spaCy
Correct answer: NLTK
NLTK (Natural Language Toolkit) provides `word_tokenize()`, which splits a string into a list of word and punctuation tokens.
Data Science with Python Certification
A comprehensive certification that validates proficiency in Python-based data science skills including data manipulation with Pandas/NumPy, statistical analysis, machine learning, natural language processing, and time series forecasting.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds
These practice questions were written with AI tools. They are not real exam questions. We have not yet matched this exam's facts to an official source, so confirm fees, dates and rules with the exam body. Not reviewed by a subject-matter expert. Editorial policy