Informatics Practices II: Data Handling with Pandas

Units 2 and 3 of Section B2 are data handling with the Python library Pandas: the Series and the DataFrame, creating, selecting, indexing and slicing them, adding, deleting and renaming rows and columns, Boolean indexing, joining, merging and concatenating, reading and writing CSV files and MySQL tables, descriptive statistics, group by, sorting, pivoting and missing values. All the outputs below were obtained by running the code, with import pandas as pd and import numpy as np.
Overview

1. The Libraries and the Series

1 min read · 4 parts

Pandas is the library for labelled, tabular data analysis, NumPy provides fast arrays and numerical routines (Pandas is built on it), and Matplotlib draws plots. A Series is a one-dimensional labelled array: it has values and an index. It can be created from a list or array, a dictionary (keys become the index), or a scalar with an index (the scalar is repeated). For s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]), s + 5 gives 15, 25, 35, 45; s.head(2) gives the first two values, 10 and 20, and s.tail(1) the last, 40.

Selection can be by label or by position. s["b":"c"] is a label slice and includes both ends (20 and 30); s[1:3] is a position slice that excludes the end (also 20 and 30). s.loc[...] uses labels and s.iloc[...] uses positions. Arithmetic is aligned on the index: adding two Series with different labels gives NaN where a label is missing from either.

⚠️ Label slices include the end
In a position slice s[1:3] the end 3 is excluded as in Python lists, but in a label slice s["b":"c"] the last label c is included. Mixing these up is the commonest slicing error.
Label slice versus position slice
Label slice
  • s["b":"c"]
  • Includes both ends
  • s.loc[...] uses labels
  • Gives 20 and 30
Position slice
  • s[1:3]
  • Excludes the end
  • s.iloc[...] uses positions
  • Also gives 20 and 30

Pandas is the library for labelled, tabular data analysis, NumPy provides fast arrays and numerical routines (Pandas is built on it), and Matplotlib draws plots. A Series is a…

2. The DataFrame: Creating, Selecting and Changing

1 min read · 2 parts

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.

Changing a DataFrame
TaskCodeResult
Add a columndf["bonus"] = df.marks + 5bonus is 85, 70, 95, 77
Delete a columndf.drop("age", axis=1)Columns name, marks remain
Delete a rowdf.drop(0) (axis=0 by default)Row with label 0 removed
Renamedf.rename(columns={"marks": "score"})Columns name, score, age
Sortdf.sort_values("marks", ascending=False)Meena, Asha, Karan, Ravi
Join framespd.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
🧠 axis 0 and axis 1
axis=0 runs down the rows and axis=1 runs across the columns. drop("age", axis=1) removes a column, whereas drop(0) with the default axis removes a row, and concat with axis=1 puts the frames side by side.

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

1 min read · 3 parts

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().

🎯 Why n − 1 for a sample
Dividing by n − 1 corrects the tendency of a sample to understate the spread of its population. NumPy's np.var and np.std divide by n by default, so the same numbers give different answers in the two libraries unless ddof is set.
How groupby works
  1. Split rows by a columndf.groupby("age")
  2. Apply a function to each group.marks.mean()
  3. 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

1 min read

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

1 min read

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.

  1. With s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]), the values of s["b":"c"] are

    1. 20 only
    2. 20 and 30
    3. 10, 20 and 30
    4. 30 and 40
    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.
  2. For the same Series, what does s[1:3] return?

    1. the values at positions 1 and 2, that is 20 and 30
    2. the values at positions 1, 2 and 3
    3. the value 10 only
    4. an error
    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.
  3. A Series created from the dictionary {"x": 1, "y": 2} has the index

    1. 0, 1
    2. 1, 2
    3. no index
    4. x, y
    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
  1. df.iloc[1, 1] on the marks DataFrame (name Asha, Ravi, Meena, Karan; marks 80, 65, 90, 72; age 17, 18, 17, 18) returns

    1. 80
    2. 18
    3. 65
    4. Ravi
    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.
  2. Which statement correctly removes the column "age" from a DataFrame df?

    1. df.drop("age")
    2. df.drop("age", axis=1)
    3. df.drop(axis=1)
    4. df.delete("age")
    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.
  3. The mean of marks 80, 65, 90, 72 is

    1. 76.75
    2. 76.0
    3. 72
    4. 77.5
    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.
  4. For marks 80, 65, 90, 72, Pandas var() by default returns

    1. 86.69, using n
    2. 76.75
    3. 10.75
    4. 115.58, using n − 1
    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.
  5. df.groupby("age").marks.mean() on the marks DataFrame gives for age 18

    1. 85.0
    2. 72
    3. 68.5
    4. 76.75
    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.
  6. A column holds 1.0, NaN, 3.0, 4.0. What do count() and dropna() give?

    1. count 4; three values remain
    2. count 3; three values remain after dropna
    3. count 3; four values remain
    4. count 4; four values remain
    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.
  7. With keys 1, 2 in one DataFrame and 2, 3 in another, an inner merge on the key returns how many rows?

    1. 1
    2. 2
    3. 3
    4. 4
    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.
  8. In Pandas, a Series is:

    1. A one-dimensional labelled array
    2. A two-dimensional table
    3. A three-dimensional array
    4. A plotting function
    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.
  9. A Pandas DataFrame is:

    1. A two-dimensional labelled data structure of rows and columns
    2. A single list of numbers
    3. A graph
    4. A database server
    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.
  10. df.head() returns by default:

    1. The first 5 rows
    2. The last 5 rows
    3. All rows
    4. The column names only
    Show answer

    Answer: A — The first 5 rows

    head() shows the first five rows unless a number is given. tail() shows the last five.
  11. The attribute df.shape of a DataFrame with 5 rows and 3 columns gives:

    1. (5, 3)
    2. (3, 5)
    3. 15
    4. 8
    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.
  12. With s = pd.Series([5, 10, 15]), what does (s * 2).tolist() return?

    1. [10, 20, 30]
    2. [5, 10, 15, 5, 10, 15]
    3. [7, 12, 17]
    4. [25, 100, 225]
    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.
  13. In Pandas, loc and iloc differ in that:

    1. loc selects by label and iloc selects by integer position
    2. loc selects by position and iloc by label
    3. Both select only columns
    4. Both are plotting functions
    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.
  14. With s = pd.Series([2, 4, 6, 8]), the expression s[s > 4] returns the values:

    1. 6 and 8 with their index labels 2 and 3
    2. 2 and 4
    3. All four values
    4. Only the value 8
    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.
  15. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.
  16. 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:

    1. A, B and D only
    2. A and C only
    3. B, C and D only
    4. A, B, C and D
    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.
  17. The method used to count the missing (NaN) values in each column of a DataFrame df is:

    1. df.isnull().sum()
    2. df.count_all()
    3. df.missing()
    4. df.nan()
    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.
  18. With s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"]), what does s.iloc[-2:].tolist() return?

    1. [30, 40]
    2. [10, 20]
    3. [20, 30]
    4. [40]
    Show answer

    Answer: A — [30, 40]

    iloc[-2:] takes the last two positions, giving 30 and 40. [10, 20] takes the first two.
  19. 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?

    1. 60
    2. 40
    3. 30
    4. 100
    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.
  20. A column x holds the values 1, NaN, 3, NaN. What does df["x"].isnull().sum() return?

    1. 2
    2. 1
    3. 3
    4. 4
    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.
  21. pd.concat([df1, df2]) with df1 having 2 rows and df2 having 3 rows, joined with the default axis, gives a DataFrame with:

    1. 5 rows
    2. 6 rows
    3. 3 rows
    4. 2 rows
    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.
  22. 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:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    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.