Data Science with Python Certification Data Science with Python Pandas DataFrame Operations 4 — Questions and Answers
Question 1: When using df.loc[], what types of labels are used for row selection?
- Integer positions only
- Boolean arrays only
- Index labels (strings, integers as labels, etc.) (Correct answer)
- Slice objects only
Correct answer: Index labels (strings, integers as labels, etc.)
df.loc[] is label-based, using the actual index labels rather than integer positions.
Question 2: What does pd.concat([df1, df2], axis=1) do?
- Stacks df1 and df2 vertically (row-wise)
- Joins df1 and df2 side-by-side (column-wise) (Correct answer)
- Merges on common columns
- Appends df2 rows to df1
Correct answer: Joins df1 and df2 side-by-side (column-wise)
axis=1 concatenates along columns, placing DataFrames side by side.
Question 3: How do you select all rows where the DataFrame index is in a list [10, 20, 30]?
- df.loc[10:30]
- df.iloc[[10,20,30]]
- df.loc[[10,20,30]] (Correct answer)
- df[df.index in [10,20,30]]
Correct answer: df.loc[[10,20,30]]
df.loc[[10,20,30]] selects rows by their index labels from a list.
Question 4: What is the purpose of the inplace=True parameter in methods like df.drop()?
- Returns a copy of the modified DataFrame
- Modifies the DataFrame in memory without requiring reassignment (Correct answer)
- Prevents the operation from being undone
- Applies the operation to all columns at once
Correct answer: Modifies the DataFrame in memory without requiring reassignment
inplace=True modifies the existing DataFrame object directly instead of returning a new one.
Question 5: Which method would you use to rank values in a column, handling ties with average rank?
- df['col'].rank(method='average') (Correct answer)
- df['col'].sort_values().rank()
- df['col'].argsort()
- df['col'].rank(method='first')
Correct answer: df['col'].rank(method='average')
rank(method='average') assigns tied values the average of the ranks they would occupy.
Question 6: What does df.set_index('employee_id') do?
- Sorts the DataFrame by employee_id
- Creates a copy filtered to employee_id rows
- Uses the employee_id column as the row index (Correct answer)
- Adds employee_id as a new column
Correct answer: Uses the employee_id column as the row index
set_index() replaces the default integer index with the specified column, making it the row labels.
Question 7: How do you apply a custom function to each row of a DataFrame?
- df.apply(func, axis=0)
- df.apply(func, axis=1) (Correct answer)
- df.map(func)
- df.transform(func, axis=1)
Correct answer: df.apply(func, axis=1)
apply(func, axis=1) passes each row as a Series to the function; axis=0 applies column-wise.
When using df.loc[], what types of labels are used for row selection?