Informatics Practices II: Data Handling with Pandas
2. The DataFrame: Creating, Selecting and Changing
A DataFrame is a two-dimensional table of labelled rows and columns, each column a Series. It is created from a dictionary of lists or Series (keys become column names), a list of dictionaries (each dictionary a row) or by reading a file with pd.read_csv("file.csv"), and written with df.to_csv("file.csv"). For df with name = Asha, Ravi, Meena, Karan, marks = 80, 65, 90, 72 and age = 17, 18, 17, 18: df.shape is (4, 3); df.loc[2, "name"] is Meena (label row 2, column name); df.iloc[1, 1] is 65 (row position 1, column position 1); and Boolean indexing df[df.marks > 70].name gives Asha, Meena and Karan.
| Task | Code | Result |
|---|---|---|
| Add a column | df["bonus"] = df.marks + 5 | bonus is 85, 70, 95, 77 |
| Delete a column | df.drop("age", axis=1) | Columns name, marks remain |
| Delete a row | df.drop(0) (axis=0 by default) | Row with label 0 removed |
| Rename | df.rename(columns={"marks": "score"}) | Columns name, score, age |
| Sort | df.sort_values("marks", ascending=False) | Meena, Asha, Karan, Ravi |
| Join frames | pd.concat([d1, d2]) stacks rows; axis=1 sets side by side; d1.merge(d2, on="k") matches a key like a SQL join (how="inner", "outer", "left") | With keys 1, 2 and 2, 3 an inner merge has 1 row and an outer merge 3 rows |
A DataFrame is a two-dimensional table of labelled rows and columns, each column a Series. It is created from a dictionary of lists or Series (keys become column names), a list of…
3. Descriptive Statistics, Grouping, Pivoting and Missing Values
The methods max, min, count, sum, mean, median, mode, quantile, std and var work on a column. For marks 80, 65, 90, 72: mean is 76.75, median 76.0 (the average of 72 and 80), idxmax (the index of the largest) 2, and quantile(0.25), the first quartile, 70.25. Pandas std and var use n − 1 (the sample formula) by default, so std is 10.75 and var 115.58; the population variance, with ddof=0, is 86.69. count counts non-missing values only.
groupby splits rows by a column, applies a function and combines: df.groupby("age").marks.mean() gives 85.0 for age 17 and 68.5 for age 18. pivot reshapes: with city A, A, B, B, year 1, 2, 1, 2 and amount 5, 6, 7, 8, pivot(index="city", columns="yr", values="amt") puts cities in rows and years in columns, so city B in year 2 is 8; pivot_table with aggfunc="sum" aggregates duplicates (city A totals 11). Missing values appear as NaN: isnull().sum() counts them (1 in the column 1.0, NaN, 3.0, 4.0), dropna() removes the rows (3 left) and fillna(0) replaces them with 0, or fillna(df.p.mean()) with the mean 2.67. Data can also move between MySQL and Pandas with pd.read_sql() and df.to_sql().
- Split rows by a columndf.groupby("age")
- Apply a function to each group.marks.mean()
- Combine the resultsAge 17: 85.0; age 18: 68.5
The methods max, min, count, sum, mean, median, mode, quantile, std and var work on a column. For marks 80, 65, 90, 72: mean is 76.75, median 76.0 (the average of 72 and 80), idxmax (the…
4. Worked Examples: Series and DataFrame Operations
Create s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']). The label slice s['b':'c'] gives 20 and 30, including the end label, and the position slice s[1:3] also gives 20 and 30, but excludes position 3, so the two look alike here for different reasons. s.sum() is 100 and s[s > 15] keeps b, c and d. Now a DataFrame df with columns name (Asha, Ravi, Meena), marks (80, 65, 90) and age (16, 17, 16). The expression df.marks + 5 gives 85, 70 and 95, and df[df.marks > 70] returns the rows for Asha and Meena, indices 0 and 2, with their index labels kept. df.shape is (3, 3), df.loc[1, 'name'] is Ravi, and df.iloc[0, 1] is 80, the first row and second column by position.
Grouping splits the table by a column and summarises each part. df.groupby('age').marks.mean() returns 85.0 for age 16, the mean of 80 and 90, and 65.0 for age 17. The mean of the marks column is 78.33 and its sample standard deviation, which divides by n − 1, is 12.58. Notice that boolean selection and label selection return different things: a condition returns a filtered DataFrame, while loc and iloc return a single value or a slice according to label or position.
Create s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']). The label slice s['b':'c'] gives 20 and 30, including the end label, and the position slice s[1:3] also gives 20 and 30…
Missing Values and Aggregation in Practice
Real data often has gaps, and pandas marks a missing number as NaN. Methods such as isnull() show where the gaps are, dropna() removes the incomplete rows, and fillna(0) replaces each gap with a chosen value. Aggregation methods like sum(), mean() and count() skip NaN by default, which means count() can be smaller than the number of rows. For a column holding 10, 20, NaN and 30, mean() is 20, the average of the three real values, while count() is 3 although the column has four entries. A student who forgets this will compute the average over four values and get the wrong answer. The same care applies to groupby, where each group's statistics ignore its own missing entries.
Real data often has gaps, and pandas marks a missing number as NaN. Methods such as isnull() show where the gaps are, dropna() removes the incomplete rows, and fillna(0) replaces each gap…
Key takeaways
- A Series is a one-dimensional labelled array and a DataFrame a two-dimensional table; a Series can come from a list, array, dictionary or scalar.
- A label slice s["b":"c"] includes the end; a position slice s[1:3] excludes it; loc uses labels and iloc uses positions.
- Boolean indexing df[df.marks > 70] selects rows; drop with axis=1 removes columns; rename, sort_values, concat and merge reshape and join frames.
- Pandas std and var divide by n − 1 by default; mean, median, quantile, count and idxmax summarise a column; count skips NaN.
- groupby aggregates by group, pivot and pivot_table reshape; dropna and fillna handle missing values; read_csv, to_csv, read_sql and to_sql move data in and out.
Practice questions (25)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
With s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]), the values of s["b":"c"] are
Show answer
Answer: B — 20 and 30
A label slice includes both end labels, so b and c give 20 and 30. The position slice s[1:3] happens to give the same two values.For the same Series, what does s[1:3] return?
Show answer
Answer: A — the values at positions 1 and 2, that is 20 and 30
Position slicing excludes the end position 3, as list slicing does in Python. The result keeps the index labels b and c.A Series created from the dictionary {"x": 1, "y": 2} has the index
Show answer
Answer: D — x, y
The dictionary keys become the index labels and the values become the data. A list would have the default index 0, 1.
Show the other 22 questions
df.iloc[1, 1] on the marks DataFrame (name Asha, Ravi, Meena, Karan; marks 80, 65, 90, 72; age 17, 18, 17, 18) returns
Show answer
Answer: C — 65
iloc[1, 1] is the second row, second column, that is Ravi's marks, 65. Column position 0 is name and position 2 is age.Which statement correctly removes the column "age" from a DataFrame df?
Show answer
Answer: B — df.drop("age", axis=1)
axis=1 tells drop to look for a column; without it, drop looks for a row label "age" and raises a KeyError.The mean of marks 80, 65, 90, 72 is
Show answer
Answer: A — 76.75
The sum is 307 and 307 ÷ 4 = 76.75. The median, 76.0, is the average of the middle two values 72 and 80.For marks 80, 65, 90, 72, Pandas var() by default returns
Show answer
Answer: D — 115.58, using n − 1
The squared deviations sum to 346.75; 346.75 ÷ 3 = 115.58 (sample), and 346.75 ÷ 4 = 86.69 (population). 10.75 is the sample standard deviation, the square root of 115.58.df.groupby("age").marks.mean() on the marks DataFrame gives for age 18
Show answer
Answer: C — 68.5
Ravi (65) and Karan (72) are 18, and (65 + 72) ÷ 2 = 68.5. Age 17 holds Asha (80) and Meena (90), mean 85.0.A column holds 1.0, NaN, 3.0, 4.0. What do count() and dropna() give?
Show answer
Answer: B — count 3; three values remain after dropna
count counts only non-missing entries, and dropna removes the missing one. The length is still 4, but count is 3.With keys 1, 2 in one DataFrame and 2, 3 in another, an inner merge on the key returns how many rows?
Show answer
Answer: A — 1
Only key 2 is present in both. An outer merge would keep all keys, 1, 2 and 3, giving 3 rows.In Pandas, a Series is:
Show answer
Answer: A — A one-dimensional labelled array
A Series holds one column of data with an index. A two-dimensional table is a DataFrame.A Pandas DataFrame is:
Show answer
Answer: A — A two-dimensional labelled data structure of rows and columns
A DataFrame is like a table with labelled rows and columns. A single labelled list is a Series.df.head() returns by default:
Show answer
Answer: A — The first 5 rows
head() shows the first five rows unless a number is given. tail() shows the last five.The attribute df.shape of a DataFrame with 5 rows and 3 columns gives:
Show answer
Answer: A — (5, 3)
shape is the tuple (number of rows, number of columns). (3, 5) swaps the order and 15 is the number of cells.With s = pd.Series([5, 10, 15]), what does (s * 2).tolist() return?
Show answer
Answer: A — [10, 20, 30]
Multiplying a Series applies the operation to each element. Repetition of the list happens only for a plain Python list.In Pandas, loc and iloc differ in that:
Show answer
Answer: A — loc selects by label and iloc selects by integer position
loc is label-based and iloc is position-based. Option 2 reverses them, the usual mix-up.With s = pd.Series([2, 4, 6, 8]), the expression s[s > 4] returns the values:
Show answer
Answer: A — 6 and 8 with their index labels 2 and 3
Boolean selection keeps the elements greater than 4 along with their original labels. 2 and 4 are the values that fail the condition.Assertion (A): Adding two Series with different index labels produces NaN for non-matching labels.
Reason (R): Pandas aligns the values on the index labels and a label present in only one Series has nothing to be added to.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Alignment on labels is what leaves unmatched ones as NaN, as R states. Option 2 is wrong.Consider the following statements:
A. Different columns of a DataFrame can hold different data types.
B. A Series has an index.
C. A DataFrame is always one-dimensional.
D. df.describe() gives summary statistics of numeric columns.
Choose the correct answer:Show answer
Answer: A — A, B and D only
A, B and D are correct. C is false because a DataFrame is two-dimensional, so option 4 is the trap.The method used to count the missing (NaN) values in each column of a DataFrame df is:
Show answer
Answer: A — df.isnull().sum()
isnull() marks missing cells with True and sum() adds them per column. The other names do not exist in Pandas.With s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]), what does s.iloc[-2:].tolist() return?
Show answer
Answer: A — [30, 40]
iloc[-2:] takes the last two positions, giving 30 and 40. [10, 20] takes the first two.A DataFrame has columns dept = [A, B, A, B] and sal = [10, 20, 30, 40]. What does df.groupby("dept").sal.sum() give for B?
Show answer
Answer: A — 60
The B rows have salaries 20 and 40, which add to 60. 40 is the total for A, and 100 is the total of everything.A column x holds the values 1, NaN, 3, NaN. What does df["x"].isnull().sum() return?
Show answer
Answer: A — 2
Two entries are missing, and True counts as 1 when summed. 4 counts all rows and 3 counts the non-missing plus one.pd.concat([df1, df2]) with df1 having 2 rows and df2 having 3 rows, joined with the default axis, gives a DataFrame with:
Show answer
Answer: A — 5 rows
The default axis 0 stacks the rows one under the other, 2 + 3 = 5. 6 multiplies instead of adding.Assertion (A): df["total"] = df["a"] + df["b"] creates a new column holding the row-wise sums.
Reason (R): Operations between two columns are applied element by element for each row.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Element-wise operation on aligned rows gives the row-wise sums, as R states. Option 2 is wrong.