Data Science with Python Certification Data Science with Python Pandas DataFrame Operations 5 — Questions and Answers
Question 1: What does df.resample('M').sum() require the DataFrame's index to be?
- An integer RangeIndex
- A DatetimeIndex (Correct answer)
- A CategoricalIndex
- A MultiIndex
Correct answer: A DatetimeIndex
resample() is a time-based groupby and requires the index to be a DatetimeIndex.
Question 2: Which of the following creates a DataFrame with a MultiIndex from a groupby result?
- df.groupby(['city','dept']).mean() (Correct answer)
- df.groupby(['city','dept']).mean().reset_index()
- df.set_index(['city','dept'])
- df.pivot('city','dept','value')
Correct answer: df.groupby(['city','dept']).mean()
Grouping by multiple columns without reset_index() yields a DataFrame with a MultiIndex on the rows.
Question 3: What is the effect of df.clip(lower=0, upper=100) on a DataFrame?
- Drops rows with values outside 0–100
- Replaces values below 0 with 0 and above 100 with 100 (Correct answer)
- Normalizes all values to the 0–100 range
- Filters columns whose mean is in 0–100
Correct answer: Replaces values below 0 with 0 and above 100 with 100
clip() caps values at the specified lower and upper bounds without removing any rows.
Question 4: How do you stack the innermost column level of a DataFrame with MultiIndex columns to rows?
- df.unstack()
- df.melt()
- df.stack() (Correct answer)
- df.pivot()
Correct answer: df.stack()
stack() pivots the innermost column level into the innermost row level, creating a taller DataFrame.
Question 5: What does df.nlargest(5, 'revenue') return?
- The 5 rows with the smallest revenue values
- The 5 rows with the largest revenue values, sorted descending (Correct answer)
- The 5 largest unique revenue values as a Series
- A boolean mask for the top 5 revenue rows
Correct answer: The 5 rows with the largest revenue values, sorted descending
nlargest(n, column) selects the n rows with the highest values in the specified column, sorted in descending order.
Question 6: Which parameter in pd.read_csv() specifies which column to use as the row index?
- row_index
- index_col (Correct answer)
- set_index
- use_index
Correct answer: index_col
index_col accepts a column name or integer position and sets that column as the DataFrame's index on import.
Question 7: What is the correct way to check if any NaN values exist in an entire DataFrame?
- df.isna().any()
- df.isna().any().any() (Correct answer)
- df.isnull().sum() > 0
- df.hasna()
Correct answer: df.isna().any().any()
df.isna().any() returns a boolean Series per column; chaining .any() again collapses it to a single True/False.
What does df.resample('M').sum() require the DataFrame's index to be?