Tidying the Feedback Forms

Data with PythonMedium+20 XP+20

Tidying the Feedback Forms

A community centre's feedback form asks for a name, a town and an age. The replies arrive as a list of dictionaries — the shape a DataFrame is built from — and they are messy in exactly the ways this chapter warned about:

Ana sent her reply twice, typed differently each time. Ben skipped his age.

Task: write clean_replies(replies) in plain Python (no pandas needed). Return the cleaned replies as a list of dictionaries with the same three keys, where:

  • Text is tidy. Every name and town has spaces removed from both ends and is then put in title case — what .str.strip().str.title() does to a column — so " ANA" becomes "Ana" and "MILTON KEYNES " becomes "Milton Keynes".
  • Each reply appears once. Two replies are the same when their tidied name, tidied town and age all match. A missing age matches only another missing age, as with drop_duplicates. Keep the first copy, and keep the replies in their original order.
  • No age is missing. Each missing age (None) is filled with the mean of the known ages, counting every reply once — a repeated reply must not count twice. Round the fill value to 4 decimal places. If no age is known at all, leave the gaps as None.

Known ages stay exactly as they are.

Example

Ben's age is the mean of Ana's, Cara's and Dev's: (30+27+42)/3=33(30 + 27 + 42) / 3 = 33(30+27+42)/3=33.

Examples

replies = [{"name": "Ana", "town": "leeds", "age": 30}, {"name": "ben ", "town": "York", "age": None}, {"name": " ANA", "town": "Leeds ", "age": 30}, {"name": "Cara", "town": "york", "age": 27}, {"name": "Dev", "town": "LEEDS", "age": 42}]
returns [{'name': 'Ana', 'town': 'Leeds', 'age': 30}, {'name': 'Ben', 'town': 'York', 'age': 33.0}, {'name': 'Cara', 'town': 'York', 'age': 27}, {'name': 'Dev', 'town': 'Leeds', 'age': 42}]
replies = [{"name": "Iris", "town": "Bath", "age": None}, {"name": "jon", "town": " hull", "age": 25}, {"name": "IRIS ", "town": "bath", "age": None}, {"name": "Kim", "town": "Hull", "age": 33}, {"name": "Lou", "town": "bath ", "age": 37}]
returns [{'name': 'Iris', 'town': 'Bath', 'age': 31.6667}, {'name': 'Jon', 'town': 'Hull', 'age': 25}, {'name': 'Kim', 'town': 'Hull', 'age': 33}, {'name': 'Lou', 'town': 'Bath', 'age': 37}]

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