Calculations and New Columns
Learning Objectives
- You can calculate and interpret a total and an arithmetic mean for selected observations.
- You can use a function parameter to select observations and return their summary.
- You can calculate a new column while preserving the input table.
A selection identifies the records that answer a question. This chapter introduces two kinds of calculation: a summary gives one result for those records, while a calculated column gives a new value for each row.
Use the original 24-row sessions.csv from Tables and DataFrames. Start analysis.py with:
import pandas as pd
sessions = pd.read_csv("sessions.csv")Totals and Averages
A selected column has methods for calculating summaries. Add the following lines to select Programming sessions and calculate their total and average duration:
mask = sessions["subject"] == "Programming"selected = sessions[mask]print(selected["minutes"].sum())print(selected["minutes"].mean())print(len(selected))The output is:
35035.010sum() adds the ten durations to give 350 minutes. mean() calculates their arithmetic average: 350 / 10 is 35.0. The total answers how much time was recorded; the mean answers how long a session was on average. Neither calculation changes the stored durations.
A mean of 35 minutes does not mean that every session lasted 35 minutes. The contributing sessions range from 20 to 50 minutes. With this complete table, every selected row contributes one duration to the mean.
Practise the two summary methods before using a total in a function:
An empty selection has a row count of zero and a total duration of zero. It has no average session length to report. Check the row count before interpreting its mean; a later chapter considers missing durations too.
A Total for a Requested Subject
The preceding calculations use a fixed subject name. A function parameter lets the caller choose the subject. This example counts matching sessions:
def count_for_subject(sessions, subject): mask = sessions["subject"] == subject selected = sessions[mask] return len(selected)
print(count_for_subject(sessions, "Programming"))print(count_for_subject(sessions, "Physics"))The output is:
100The parameter subject supplies the value for the comparison. The function selects the rows and returns one number; the caller prints it. No Physics sessions match, so that call returns zero.
The next exercise asks for the selected sessions’ total minutes rather than their count. Use the same parameter-and-selection pattern with the column calculation you just practised. Complete subject names are compared as strings: "Programming" and "programming" differ. An empty selection’s total is zero, so it needs no separate calculation.
Minutes for One Subject
0 / 20 points
Complete minutes_for_subject(sessions, subject). Return the total minutes from rows whose complete subject equals the parameter subject.
Subject names are case-sensitive. Return numeric zero if no row matches or the table is empty. Leave sessions unchanged. The table contains the columns subject and minutes; durations are numeric and have no missing values.
Calculating a Column
Column values can also take part in ordinary arithmetic. To express durations in hours, divide each number of minutes by 60. This small table uses durations whose conversions you can check by hand:
durations = pd.DataFrame([ {"subject": "Programming", "minutes": 30}, {"subject": "Mathematics", "minutes": 90}, {"subject": "Languages", "minutes": 0}])
with_hours = durations.copy()with_hours["hours"] = with_hours["minutes"] / 60print(with_hours)The output is:
subject minutes hours0 Programming 30 0.51 Mathematics 90 1.52 Languages 0 0.0The division operates on every value in the minutes Series. Assigning the result to with_hours["hours"] adds a column with one calculated value per row. The existing columns and index labels remain in place. The unit changes from minutes to hours; the amount of recorded time is the same. Later, we will use this conversion to present results in hours, with labels that state the new unit.
durations.copy() creates the separate table before the new column is assigned. durations therefore still has only subject and minutes. Without that copy, adding a column directly to durations would change the caller’s table, just as updating a dictionary field changes that record.
The following exercise asks for the converted values in a new table. Preserve the original measurements as well as the calculated hours.
Session Durations in Hours
0 / 20 points
Complete add_hours(sessions). Return a new DataFrame with an hours column calculated by dividing minutes by 60. For example, 90 minutes gives 1.5 hours.
Keep all original columns and rows, their order, and their index labels; append hours after the existing columns. Leave sessions unchanged. It has no hours column yet, and its durations are nonnegative numbers with no missing values. An empty input still gets the new column.
We can now summarize a selection and calculate a value for every row. The next chapter extends the summary operation to produce one result for each subject.
Check Your Understanding
- How could two selections have the same mean duration but different totals?
- What does an empty selection tell you about matching sessions, and why should its mean not be reported as zero?
- How does copying before adding an
hourscolumn help a function leave its input unchanged?