1. Learn
  2. /
  3. Courses
  4. /
  5. Analyzing US Census Data in Python

Exercise

Calculating D Using Grouping in Pandas

Performing a calculation over subsets of a DataFrame is so common that pandas gives us an alternative to doing it in a loop, the groupby method. In the sample code, groupby is used first to group tracts by state, i.e. those rows having the same value in the "state" column. The sum() method is applied by group to the columns.

This exercise also makes use of merge, another useful pandas method, to join the grouped sums to the individual tracts. Don't worry about the syntax for now. merge will be explained in a later lesson.

pandas has been imported using the usual alias, and the tracts DataFrame with population columns white and black has been loaded. The variables w and b have been defined with the column names "white" and "black".

Instructions

100 XP
  • Create sums_by_state using groupby and print the result.
  • Create tracts using merge and print the result.
  • Calculate \(\left\lvert\frac{a_i}{A} - \frac{b_i}{B}\right\rvert\) and store it in a new column D. (Reminder: The sum of White and Black populations (\(A\) and \(B\)) was already calculated and is available in the tracts DataFrame in the columns suffixed with "_sum").
  • Sum the column D by state using the groupby method, and multiply by 0.5.