Data Science with Python Certification Data Science with Python Pandas DataFrame Operations 3 — Questions and Answers
Question 1: What is the default behavior of pd.merge() when no 'how' argument is specified?
- Left join
- Right join
- Inner join (Correct answer)
- Outer join
Correct answer: Inner join
pd.merge() defaults to an inner join, returning only rows with matching keys in both DataFrames.
Question 2: Which method converts a DataFrame column to the 'category' dtype?
- df['col'].to_category()
- df['col'].astype('category') (Correct answer)
- df['col'].set_dtype('category')
- pd.Categorical(df['col'])
Correct answer: df['col'].astype('category')
astype('category') is the standard way to convert a column to the memory-efficient category dtype.
Question 3: What does df.groupby('dept')['salary'].transform('mean') return?
- A Series with one mean value per department
- A Series the same length as df with each row replaced by its group mean (Correct answer)
- A DataFrame of department means
- The global mean salary
Correct answer: A Series the same length as df with each row replaced by its group mean
transform broadcasts the group-level result back to the original DataFrame's index, preserving its length.
Question 4: How do you forward-fill missing values in a DataFrame?
- df.fillna(method='bfill')
- df.fillna(method='ffill') (Correct answer)
- df.interpolate('zero')
- df.dropna(how='any')
Correct answer: df.fillna(method='ffill')
fillna(method='ffill') propagates the last valid observation forward to fill NaN values.
Question 5: What is the output type of df.groupby('category').agg({'price': ['min','max']})?
- A Series with MultiIndex
- A DataFrame with MultiIndex columns (Correct answer)
- A dictionary
- A flat DataFrame with renamed columns
Correct answer: A DataFrame with MultiIndex columns
Passing a list of functions to agg creates a DataFrame with MultiIndex columns (column name, function name).
Question 6: Which attribute returns the index labels of a DataFrame?
- df.keys()
- df.columns
- df.index (Correct answer)
- df.labels
Correct answer: df.index
df.index holds the row labels (index), while df.columns holds the column labels.
Question 7: What does df.assign(tax=df['price'] * 0.1) return?
- Modifies df in-place by adding a 'tax' column
- Returns a new DataFrame with a 'tax' column added (Correct answer)
- Raises an error if 'tax' already exists
- Returns only the 'tax' Series
Correct answer: Returns a new DataFrame with a 'tax' column added
assign() always returns a new DataFrame with the added or overwritten column, leaving the original unchanged.
What is the default behavior of pd.merge() when no 'how' argument is specified?