Data machine: Computed field

Summary

Write a function that adds a new field to records in a data set (a list of dictionaries), based on existing fields.

Situation

You have a data set (a list of dictionaries) that's missing a field you need, but it can be computed from other fields.

Action

Write a function that will loop through a data set. For each record, it computes a new value based on existing fields, and adds it to the record.

Call it like this:

  • compute_change(cleaned_goat_scores)

The function doesn't return a new data set. It modifies the data set passed as a param.

Here's an example:

  1. def compute_change(goat_scores):
  2.     '''
  3.     Add score differences to the data set.
  4.     The data is changed in-place.
  5.  
  6.     Parameters
  7.     ----------
  8.     goat_scores : list
  9.         A list of dictionaries with the goats' score.
  10.     '''
  11.     # Loop over list.
  12.     for goat_record in goat_scores:
  13.         # Compute difference.
  14.         change = goat_record['After'] - goat_record['Before']
  15.         # Add difference field to the dictionary.
  16.         goat_record['Difference'] = change
Where referenced