The Whole Survey, Cleaned

Data with PythonHard+10 XP+10

The Whole Survey, Cleaned

A community centre's feedback survey arrives as CSV text with a header row and the columns name, age, town and rating:

text
1name,age,town,rating
2Ana,34, leeds,4
3Ben,,York,5
4ana ,34,Leeds,4
5Dev,41,Bath,five

It has every problem from this module: blank ages, towns and names typed with stray spaces and odd capitals, replies saved twice, and ratings typed as words. name and town are never blank.

Write clean_survey(path). The starter code includes write_text(path, text), which saves the CSV text to a file and returns its path. Each test passes that path straight to clean_survey. Read the file with pd.read_csv(path), then clean it in this order:

  1. Tidy the text. Strip spaces from both ends of every name and town, then put them in title case.
  2. Drop repeats. Remove rows that are exact copies of an earlier row (after tidying), keeping the first.
  3. Fix the ratings. Convert rating to numbers. Anything that can't be read becomes missing.
  4. Fill the ages. Fill each missing age with the mean of the known ages (after step 2).

Return a dictionary:

  • "towns": the different towns, in the order they first appear
  • "ages": every age after filling, in row order, each rounded to 1 decimal place. If no age is known at all, the missing ones stay as None.
  • "mean_rating": the mean of the ratings that could be read, rounded to 2 decimal places, or None if none could be read
  • "missing_ratings": how many ratings could not be read, as a whole number

Examples

path = write_text("s1.csv", "name,age,town,rating\nAna,34, leeds,4\nBen,,York,5\nCara,29,LEEDS ,3\nDev,41,Bath,five\nAna,34, leeds,4\nEli,27,york,2\n")
returns {'towns': ['Leeds', 'York', 'Bath'], 'ages': [34.0, 32.8, 29.0, 41.0, 27.0], 'mean_rating': 3.5, 'missing_ratings': 1}
path = write_text("s2.csv", "name,age,town,rating\nAna,34, leeds,4\nBen,,York,5\nana ,34,Leeds,4\nDev,41,Bath,five\n")
returns {'towns': ['Leeds', 'York', 'Bath'], 'ages': [34.0, 37.5, 41.0], 'mean_rating': 4.5, 'missing_ratings': 1}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run