Data Science with Python Certification Introduction to Python for Data Science 4 — Questions and Answers
Question 1: What is the difference between `df.loc[]` and `df.iloc[]` in pandas?
- `loc` uses integer positions; `iloc` uses labels
- `loc` uses labels; `iloc` uses integer positions (Correct answer)
- They are identical in behavior
- `loc` is faster; `iloc` is for large datasets
Correct answer: `loc` uses labels; `iloc` uses integer positions
`loc` is label-based indexing while `iloc` is strictly integer position-based, which matters when index labels are not sequential integers.
Question 2: Which method in pandas returns the number of missing values per column?
- df.count_nan()
- df.isna().sum() (Correct answer)
- df.missing()
- df.null_count()
Correct answer: df.isna().sum()
`df.isna()` returns a boolean DataFrame and `.sum()` aggregates True values (NaN) per column.
Question 3: In Python, what does `*args` in a function signature allow?
- Passing keyword arguments only
- Passing a variable number of positional arguments (Correct answer)
- Unpacking a single tuple argument
- Accepting only numeric arguments
Correct answer: Passing a variable number of positional arguments
`*args` collects any number of positional arguments passed to a function into a tuple.
Question 4: What does `np.nan == np.nan` evaluate to in Python?
- True
- False (Correct answer)
- None
- Raises ValueError
Correct answer: False
By IEEE 754 standard, NaN is not equal to itself; use `np.isnan()` to test for NaN values.
Question 5: Which Python library provides the `train_test_split` function for splitting datasets?
- numpy
- pandas
- sklearn.model_selection (Correct answer)
- scipy.stats
Correct answer: sklearn.model_selection
`train_test_split` is part of scikit-learn's `model_selection` module and splits arrays into random train/test subsets.
Question 6: What is a Python generator and how does it differ from a regular function?
- A generator runs in parallel; a function runs sequentially
- A generator uses `yield` to produce values lazily; a function returns all values at once (Correct answer)
- A generator cannot accept arguments; a function can
- A generator always returns a list; a function returns a single value
Correct answer: A generator uses `yield` to produce values lazily; a function returns all values at once
Generators use `yield` to produce values one at a time on demand, making them memory-efficient for large datasets.
Question 7: Which pandas method fills missing values with a specified value or method?
- df.replace_na()
- df.fillna() (Correct answer)
- df.impute()
- df.replace_null()
Correct answer: df.fillna()
`df.fillna(value)` replaces NaN entries with the specified value, or with forward/backward fill strategies.
What is the difference between `df.loc[]` and `df.iloc[]` in pandas?