Data Science with Python Certification Data Science with Python Pandas DataFrame Operations 2 — Questions and Answers
Question 1: Which method returns the number of non-null values in each column of a DataFrame?
- df.size()
- df.count() (Correct answer)
- df.notnull().sum()
- df.shape()
Correct answer: df.count()
df.count() returns the count of non-null values per column by default.
Question 2: What does df.pivot_table(values='sales', index='region', aggfunc='mean') compute?
- Sum of sales per region
- Mean sales per region (Correct answer)
- Count of rows per region
- Median sales per region
Correct answer: Mean sales per region
The aggfunc='mean' parameter computes the average of the 'sales' column grouped by 'region'.
Question 3: How do you rename columns 'a' and 'b' to 'x' and 'y' in a DataFrame df?
- df.rename({'a':'x','b':'y'})
- df.rename(columns={'a':'x','b':'y'}) (Correct answer)
- df.columns = {'a':'x','b':'y'}
- df.set_columns({'a':'x','b':'y'})
Correct answer: df.rename(columns={'a':'x','b':'y'})
df.rename(columns={...}) accepts a mapping dict via the columns keyword argument.
Question 4: What is the result of df.duplicated() on a DataFrame?
- Drops all duplicate rows
- Returns a boolean Series marking duplicate rows (Correct answer)
- Returns only duplicate rows
- Counts duplicates per column
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 5: Which of the following correctly filters rows where column 'age' is between 18 and 35 (inclusive)?
- df[df['age'] > 18 & df['age'] < 35]
- df[df['age'].between(18, 35)] (Correct answer)
- df[df['age'] in range(18, 36)]
- df.filter(age=(18,35))
Correct answer: df[df['age'].between(18, 35)]
The .between(left, right) method returns True for values within the inclusive range.
Question 6: What does df.melt(id_vars=['id'], value_vars=['q1','q2']) do?
- Pivots wide data to wide format
- Transforms wide data to long format (Correct answer)
- Merges two DataFrames
- Removes columns q1 and q2
Correct answer: Transforms wide data to long format
df.melt() unpivots a DataFrame from wide to long format, keeping id_vars fixed and stacking value_vars.
Question 7: How do you compute a rolling 7-day mean on column 'price' in a DataFrame df?
- df['price'].mean(window=7)
- df['price'].rolling(7).mean() (Correct answer)
- df['price'].resample('7D').mean()
- df['price'].shift(7).mean()
Correct answer: df['price'].rolling(7).mean()
rolling(7).mean() computes a sliding window average over 7 consecutive observations.
Which method returns the number of non-null values in each column of a DataFrame?