Skip to main content

A 40 GB CSV of transactions does not fit in memory. Compute the average amount per city with pandas. For example, the result should be one row per city with its mean amount, the same as if the whole file had been loaded.

Coding rounds · Intermediate 2

Short answer

Read the file in chunks with pd.read_csv(path, usecols=["city", "amount"], chunksize=1_000_000). For each chunk compute the sum and count per city, add them to running totals, and divide at the end. Time is O(n) in rows; memory is one chunk plus one row per city. Do not average the chunk averages.

Deeper answer

First clarify the task. Ask which columns are needed, whether the result is small, such as one row per city, and whether this is a single job or runs daily. Ask whether another format or tool is allowed.

The steps are: loop with for chunk in pd.read_csv(path, usecols=["city", "amount"], chunksize=1_000_000). Reading two columns instead of all of them already cuts memory a lot. In each chunk compute part = chunk.groupby("city")["amount"].agg(["sum", "count"]). Combine with totals = totals.add(part, fill_value=0), where fill_value handles a city that is absent from one chunk. After the loop, the mean is totals["sum"] / totals["count"].

The key point is that a mean of chunk means is wrong when chunks hold different numbers of rows per city, so you carry sums and counts. This works for sum, count, min and max; a median needs another method. Test with a small file and chunksize 3, and compare against the result of loading it all. Say that the dtype argument and category columns shrink memory further, and that for repeated work you would convert to Parquet or use DuckDB or Polars.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Tables with pandas

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.