Working with DataFrames — quiz
10 questions covering this module. Loading, inspecting, selecting and filtering.
How do you stop 07030 becoming 7030?
- astype(int)
- dtype={'zip': str} when reading
- parse_dates
- encoding="utf-8"
Answer: dtype={'zip': str} when reading — Read identifier-like columns as strings.
pd.read_excel(..., sheet_name=None) returns:
- The first sheet
- A dictionary of every sheet
- An error
- An empty DataFrame
Answer: A dictionary of every sheet — Keyed by sheet name.
info() shows order_date as object. This means:
- It is a date
- It is stored as text
- It contains nulls
- It is an index
Answer: It is stored as text — object means text; convert with to_datetime.
An integer column showing float64 usually indicates:
- A bug
- Missing values are present
- Large numbers
- Wrong encoding
Answer: Missing values are present — NaN forces the column to float.
df[['a']] returns:
- A Series
- A DataFrame
- A list
- An index
Answer: A DataFrame — Double brackets always give a DataFrame.
df.rename(columns={...}) without assignment:
- Renames in place
- Returns a new DataFrame and changes nothing
- Raises an error
- Renames the index
Answer: Returns a new DataFrame and changes nothing — Assign the result, or pass inplace=True.
df[df['a'] > 1 and df['b'] < 5] raises an error because:
- a is not numeric
- pandas requires & rather than and
- Brackets are wrong
- It needs .loc
Answer: pandas requires & rather than and — The "truth value is ambiguous" error means and was used instead of &.
df.loc[0:5] versus df.iloc[0:5]:
- Identical
- loc includes row 5, iloc excludes it
- iloc includes 5, loc excludes it
- loc only takes conditions
Answer: loc includes row 5, iloc excludes it — loc is label-based and slice-inclusive.
Which handles several conditions in order?
- np.where
- np.select
- apply
- astype
Answer: np.select — np.select takes condition and choice lists, first match wins.
SettingWithCopyWarning is best fixed by:
- Ignoring it
- Adding .copy() after filtering, or assigning via df.loc
- Using apply
- Resetting the index
Answer: Adding .copy() after filtering, or assigning via df.loc — It means pandas cannot tell whether you hold a view or a copy.