Unit 9: Handling data with pandas - Practice Quiz
1 What is pandas mainly used for in Python?
2 Which statement commonly imports pandas using its standard alias?
using pandas as py
include pandas as pd
import pandas as pd
import pandas as py
3 What is a pandas Series?
4 Which expression creates a pandas Series from a Python list?
pd.sort_values([10, 20, 30])
pd.Series([10, 20, 30])
pd.read_csv([10, 20, 30])
pd.DataFrame([10, 20, 30])
5 What does the index of a pandas Series contain?
6 What is a pandas DataFrame?
7 In a DataFrame, what do columns usually represent?
8
Which expression creates a DataFrame from a dictionary named data?
pd.TableSeries(data)
pd.readFrame(data)
pd.SeriesFrame(data)
pd.DataFrame(data)
9
What does the shape attribute of a DataFrame return?
10
By default, what does df.head() display?
11 Which DataFrame method sorts rows according to the values in a column?
sort_values()
reset_index()
value_counts()
sort_index()
12 Which argument sorts DataFrame values in descending order?
ascending=True
reverse=False
ascending=False
descending=False
13 Which method sorts a DataFrame according to its index labels?
set_index()
drop_index()
sort_index()
sort_values()
14 Which pandas function reads data from a CSV file?
pd.import_csv()
pd.load_csv()
pd.open_csv()
pd.read_csv()
15 Which DataFrame method writes data to a CSV file?
to_csv()
export_csv()
write_csv()
save_csv()
16
What is the purpose of index=False in df.to_csv("data.csv", index=False)?
17
If df is a DataFrame, what does df["Age"] usually return?
Age
Age
Age
Age
18
Which statement creates a new column named Total by adding columns A and B?
df("Total") = df("A") + df("B")
df["A"] = df["Total"] + df["B"]
df["Total"] = df["A"] + df["B"]
df.add("Total", "A", "B")
19 Which DataFrame method removes rows containing missing values by default?
dropna()
fillna()
isna()
notna()
20
What does df.describe() commonly provide for numerical columns?
21 Which statement correctly imports pandas using its conventional alias and creates a labeled one-dimensional object?
import pandas as pd; s = pd.Series([10, 20])
from pandas import pd; s = pd.Array([10, 20])
import pandas as pn; s = pd.DataFrame([10, 20])
import pandas; s = pandas.Table([10, 20])
22
Given s1 = pd.Series([10, 20], index=['a', 'b']) and s2 = pd.Series([1, 2], index=['b', 'c']), what is the result of s1 + s2?
10, 21, and 2 at indices a, b, and c
11 and 22 at indices a and b
21 only at index b
NaN, 21, and NaN at indices a, b, and c
23
For s = pd.Series([8, 12, 16], index=['x', 'y', 'z']), which expression returns the first two values by position?
s.iloc[1:3]
s.loc['x':'x']
s.loc[0:1]
s.iloc[0:2]
24
What columns and number of rows are produced by pd.DataFrame({'name': ['Ana', 'Bo'], 'score': [80, 90]})?
Ana and Bo, with 2 rows
name and score, with 4 rows
name and score, with 2 rows
25
A DataFrame df contains columns name, age, and city. Which expression returns a DataFrame containing only name and city?
df['name', 'city']
df.iloc['name', 'city']
df[['name', 'city']]
df.loc['name', 'city']
26
Which expression selects rows where score is at least 70 and attempts is less than 3?
df[df['score'] >= 70 and df['attempts'] < 3]
df[(df['score'] >= 70) | (df['attempts'] < 3)]
df[df['score'] >= 70, df['attempts'] < 3]
df[(df['score'] >= 70) & (df['attempts'] < 3)]
27
A DataFrame has numeric columns price and quantity. Which statement creates a total column containing their row-wise products?
df['total'] = df[['price', 'quantity']].product()
df['total'] = df['price'] * df['quantity']
df['total'] = df[['price', 'quantity']].sum()
df['total'] = df['price'] + df['quantity']
28
Which command sorts df by department in ascending order and then by salary in descending order?
df.sort_values(['salary', 'department'], ascending=[True, False])
df.sort_values(['department', 'salary'], ascending=[False, True])
df.sort_values(['department', 'salary'], ascending=[True, False])
df.sort_index(['department', 'salary'], ascending=[True, False])
29
After filtering, a DataFrame has row labels [7, 2, 5]. Which expression sorts the rows by these labels without changing column order?
df.sort_values()
df.sort_index(axis=1)
df.reset_index(drop=True)
df.sort_index(axis=0)
30
A file students.csv contains five columns. Which command reads only the name and grade columns?
pd.read_csv('students.csv', usecols=['name', 'grade'])
pd.read_csv('students.csv', index_col=['name', 'grade'])
pd.read_csv('students.csv', columns=['name', 'grade'])
pd.read_csv('students.csv', names=['name', 'grade'])
31
The first column of sales.csv is named order_id and should become the DataFrame index. Which command does this while reading the file?
pd.read_csv('sales.csv', index_col='order_id')
pd.read_csv('sales.csv', usecols='order_id')
pd.read_csv('sales.csv', names='order_id')
pd.read_csv('sales.csv', header='order_id')
32
A CSV column named date contains values such as 2026-09-10. Which command asks pandas to convert that column to date-time values during import?
pd.read_csv('events.csv', parse_dates=['date'])
pd.read_csv('events.csv', convert_dates=['date'])
pd.read_csv('events.csv', date_col=['date'])
pd.read_csv('events.csv', dtype=['date'])
33
For a DataFrame containing only numeric values, what does df.mean(axis=1) calculate?
34
A DataFrame has columns department and salary. Which expression calculates the average salary for each department?
df.groupby('salary')['department'].mean()
df['salary'].groupby(df.index).sum()
df.groupby('department')['salary'].mean()
df.groupby('department')['salary'].count()
35
Which expression removes only rows where the email value is missing, regardless of missing values in other columns?
df.dropna(subset=['email'])
df.drop(columns=['email'])
df.dropna()
df.dropna(axis=1)
36
Which statement replaces missing values in the score column with that column's median while leaving other columns unchanged?
df = df['score'].dropna(df['score'].median())
df['score'] = df.fillna(df['score'].median())
df['score'] = df['score'].fillna(df['score'].median())
df['score'] = df['score'].replace(df['score'].mean())
37
Which expression renames the column old_name to new_name without renaming any index labels?
df.replace({'old_name': 'new_name'})
df.rename(index={'old_name': 'new_name'})
df.columns.rename({'old_name': 'new_name'})
df.rename(columns={'old_name': 'new_name'})
38
DataFrames customers and orders both contain customer_id. Which expression keeps only IDs present in both DataFrames?
customers.join(orders, how='outer')
pd.merge(customers, orders, on='customer_id', how='outer')
pd.merge(customers, orders, on='customer_id', how='inner')
pd.concat([customers, orders], axis=0)
39
A Series colors contains ['red', 'blue', 'red', 'green', 'blue', 'red']. What does colors.value_counts() return first by default?
green with count 1
red with count 3
red with count 1
blue with count 2
40
Two DataFrames jan and feb have identical columns but overlapping index labels. Which expression stacks their rows and creates a fresh sequential index?
pd.concat([jan, feb], axis=0, ignore_index=True)
pd.merge(jan, feb, how='inner', ignore_index=True)
pd.concat([jan, feb], axis=1, ignore_index=True)
jan.join(feb, axis=0, ignore_index=True)
41
Given:
left = pd.Series([10, 20], index=["a", "b"])
right = pd.Series([1, 2], index=["b", "c"])
What is (left + right).fillna(0).to_dict()?
{"a": 11.0, "b": 22.0, "c": 2.0}
{"a": 0.0, "b": 21.0, "c": 0.0}
{"a": 10.0, "b": 21.0, "c": 2.0}
{"a": 11.0, "b": 22.0, "c": 0.0}
42
Consider s = pd.Series([3, 1, 2], index=["x", "y", "x"]). Which statement about r = s["x"] is correct?
r is the scalar 3, because the first match is selected.
r is a Series whose values sum to 5.
r raises an error because index labels must be unique.
r is the scalar 2, because the last match is selected.
43
Given s = pd.Series([1, pd.NA, 3], dtype="Int64") and r = s * 2, which pair correctly describes r?
Int64, and its values are [2, 0, 6].
object, and its values are [2, None, 6].
Int64, and its values are [2, <NA>, 6].
float64, and its values are [2.0, NaN, 6.0].
44
Given:
p = pd.Series([1, 2], index=["a", "b"])
q = pd.Series([3, 4], index=["b", "c"])
df = pd.DataFrame({"p": p, "q": q})
Which result is correct?
df.shape == (3, 2) and df.loc["b"].sum() == 5
df.shape == (3, 2) and df.loc["b"].sum() == 6
df.shape == (2, 2) and df.loc["b"].sum() == 5
df.shape == (4, 2) and df.loc["b"].sum() == 5
45
Given:
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}, index=["x", "y"])
df.loc[:, ["a", "b"]] = df.loc[:, ["b", "a"]]
What are the final columns a and b?
a is [3, 2], and b is [1, 4].
a is [1, 2], and b is [3, 4].
a is [3, 4], and b is [1, 2].
a is [1, 4], and b is [3, 2].
46
Given:
df = pd.DataFrame({"v": [10, 20, 30]}, index=["a", "b", "c"])
mask = pd.Series([True, False, True], index=["c", "a", "b"])
What is df.loc[mask].index.tolist()?
["b", "c"]
["c", "b"]
["a", "c"]
["c", "a"]
47
For the DataFrame below, what is the resulting id order after df.sort_values(["a", "b"], ascending=[True, False], na_position="first")?
df = pd.DataFrame({"id": [0, 1, 2, 3], "a": [2, 1, 1, np.nan], "b": [1, 2, 1, 0]})
[0, 1, 2, 3]
[1, 2, 0, 3]
[3, 1, 2, 0]
[3, 2, 1, 0]
48
Given:
df = pd.DataFrame({"id": [0, 1, 2], "a": [-2, 1, -1], "b": [1, -3, 2]})
What is the id order produced by df.sort_values(["a", "b"], key=lambda s: s.abs())?
[0, 2, 1]
[2, 0, 1]
[1, 2, 0]
[2, 1, 0]
49 A DataFrame must be sorted by one column while preserving the original relative order of rows with equal keys. Which call explicitly provides that stability?
df.sort_values("k", kind="heapsort")
df.sort_values("k", kind="quicksort")
df.sort_values("k", kind="mergesort")
df.sort_values("k", na_position="first")
50
A CSV contains:
id,value\n001,NA\n002,\n003,null\n
Which call preserves the IDs' leading zeros and reads all three value fields as literal strings rather than missing values?
pd.read_csv(path, dtype=str, na_filter=True)
pd.read_csv(path, dtype={"id": int, "value": "string"}, na_filter=False)
pd.read_csv(path, dtype={"id": "string"}, keep_default_na=True)
pd.read_csv(path, dtype={"id": "string", "value": "string"}, keep_default_na=False)
51
A CSV has columns in the order a,b,c. What column order is normally produced by pd.read_csv(path, usecols=["c", "a"])?
["c", "b", "a"], reversing the CSV order
["a", "c"], matching the CSV file order
["c", "a"], matching the usecols list
["a", "b", "c"], retaining every CSV column
52
Suppose chunks is a list of DataFrames read from one CSV using chunksize, and chunk sizes differ. Which expression computes the exact overall mean of numeric column x, ignoring missing values?
sum(c["x"].sum() for c in chunks) / sum(c["x"].count() for c in chunks)
sum(c["x"].sum() for c in chunks) / len(chunks)
sum(c["x"].mean() for c in chunks) / sum(c["x"].count() for c in chunks)
sum(c["x"].mean() for c in chunks) / len(chunks)
53
Given the CSV text a,b\n1,10\n2,20\n3,30\n, what is the sum of column a after calling pd.read_csv(io.StringIO(text), skiprows=lambda i: i == 2)?
3
6
4
5
54
Given:
df = pd.DataFrame({"x": [1, 2], "y": [10, 20]}, index=["a", "b"])
s = pd.Series([100, 200], index=["b", "a"])
r = df.add(s, axis="index")
What is r.loc["a"].tolist() + r.loc["b"].tolist()?
[101, 210, 202, 120]
[201, 210, 102, 120]
[101, 110, 202, 220]
[201, 110, 102, 220]
55
A left DataFrame has join keys [1, 1, 2], while the right DataFrame has unique join keys [1, 2]. What is the most restrictive validate mode that permits left.merge(right, on="key", validate=...)?
"many_to_many"
"one_to_one"
"many_to_one"
"one_to_many"
56
Given:
a = pd.DataFrame({"x": [1, 2]}, index=["u", "v"])
b = pd.DataFrame({"y": [3, 4]}, index=["v", "w"])
What describes pd.concat([a, b], axis=1, join="inner")?
["v"] and values x=2, y=3 at v.
["v"] and values x=1, y=4 at v.
["u", "v", "w"] and values x=2, y=3 at v.
["u", "w"] and no row labeled v.
57
Given:
df = pd.DataFrame({"g": ["A", "A", "B"], "x": [1, 3, 10]})
What is df[df["x"] > df.groupby("g")["x"].transform("mean")]["x"].tolist()?
[10]
[3]
[1, 3]
[3, 10]
58
A DataFrame contains two rows with the same id and key pair but values 10 and 20. What happens when these columns are reshaped with df.pivot(index="id", columns="key", values="value")?
15.
ValueError is raised for duplicate entries.
10.
20.
59
Given df = pd.DataFrame({"a": [1, np.nan], "b": [np.nan, np.nan]}), what does df.sum(min_count=1) contain?
a is 0.0, and b is 0.0.
a is NaN, and b is NaN.
a is 1.0, and b is NaN.
a is 1.0, and b is 0.0.
60
Given:
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]}, index=["x", "y"])
other = pd.DataFrame({"a": [9, 8], "b": [np.nan, 7]}, index=["y", "z"])
After df.update(other), what is df.loc["y"].tolist()?
[2, 4]
[9, NaN]
[9, 4]
[8, 7]
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →