Skip to content
Module 12 of 2155 min readBeginner

AI for data analysis

From a messy CSV to defensible insight: clean, profile, summarise, chart, and explain output with AI — and catch the confidently-wrong numbers.

57%

Listen along

Read “AI for data analysis” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Learning objectives

By the end of this module, you should be able to:

  • 01Upload a messy spreadsheet to an AI data tool, get it to profile, clean, and describe the data — and inspect the code behind every number
  • 02Write prompts that standardise inconsistent categories, coerce mixed types, and surface missing values in real KNBS / World Bank-style data, with an auditable change log
  • 03Generate and critically read descriptive statistics and charts, catching mislabelled axes, misleading scales, and fabricated summary numbers
  • 04Explain a regression output in plain language and tell a defensible economic pattern apart from one AI has overfitted to noise

It is Monday morning and someone has emailed you a CSV: county-level GDP, inflation, and unemployment, pulled from a handful of KNBS releases. The county names are spelled three different ways, GDP is stored as text with thousands commas, inflation is a column of '7.1%' strings, and missing unemployment is coded as -99. A year ago you would have spent the morning in Excel by hand. AI can now do most of that cleaning in minutes — but it will also, with total confidence, hand you a wrong mean, a mislabelled axis, or a correlation it invented. This module is about getting from that messy file to insight fast, without being fooled.

Two ways AI touches your data — only one is safe

When you paste a table into a chat window, the model reads your numbers as text and pattern-matches over them. It never computes; it predicts a plausible-looking answer. Ask it for the mean of a column and it may transpose digits, skip rows, or simply make a number up that looks right. The safe mode is upload-and-run-code: tools such as ChatGPT's Advanced Data Analysis, Claude's analysis tool, Microsoft Excel Copilot, and Gemini in Google Sheets write actual code (usually pandas) and execute it on the real file. The numbers then come from computation you can read, question, and re-run. Rule of thumb: if you cannot see the code, do not trust the number.

The confidently wrong mean

The single most dangerous AI failure in data work is a fabricated summary number delivered with total confidence. A pasted-table model will report 'mean county GDP is KES 214 billion' when the true figure is KES 186 billion, and it will do so in the same calm tone it uses when it is right. It can also invent a correlation coefficient, misread which column is which, or quietly ignore the -99 sentinels dragging a mean down. Never treat an AI-produced statistic as final until you have recomputed at least one of them yourself or seen the code that produced it.

Profile before you touch anything

Do not clean first. Profile first. Before any transformation you need to know the shape of the data (rows, columns), each column's type, how much is missing and how it is coded, the distinct values in every categorical column, and the range of every numeric one. This is also how you understand your variables before you model: is 'unemployment' a rate or a count, is 'gdp' nominal or real, is a year stored as 2019 or '2019/20'? Ask the AI to profile and report — and explicitly forbid it from changing anything yet. Real KNBS and World Bank exports are messy in predictable ways, and the profile is where you catch them.

text
You are a careful data analyst working in pandas. I have uploaded a CSV. Do NOT change anything yet — profile it first, and show me the code you run.
1. Report the number of rows, the number of columns, and each column's name and inferred dtype.
2. For every column, give the count and percentage of missing values, and show the 10 most frequent values, so I can spot sentinel codes like -99, 999, 'N/A', or blank strings that are really missing.
3. For any numeric-looking column that loaded as text, tell me WHY (thousands commas, currency symbols, percent signs, stray letters) — but do not convert it yet.
4. For each categorical column, list every distinct value and its count, so I can see inconsistent spellings and casing.
5. Flag any fully duplicate rows and any duplicate (county, year) combinations.
Do not clean, impute, or drop anything until I tell you to.
  • Inconsistent categories: 'Nairobi', 'Nairobi City', and 'NAIROBI' are three labels for one county; 'Murang'a' and 'Muranga' differ by an apostrophe
  • Missing values coded many ways: blank, -99, 999, 'n/a', '-', or a stray full stop, all in the same column
  • Numbers stored as text: '1,204,915' with commas, 'KES 88bn', or '7.1%' — none of which arithmetic will touch until coerced
  • Mixed types and formats: a year as 2019 in some rows and '2019/20' in others; dates as both 03/04/2020 and 2020-04-03
  • Whitespace and casing: 'Nairobi ' with a trailing space is not equal to 'Nairobi'
  • Duplicate county-year rows from stitching several releases together, sometimes with conflicting values

Cleaning — and diffing what changed

Diff, don't trust

The cardinal sin is a silent clean. If AI standardises names, coerces numbers, and drops rows in one invisible step, it may have merged two distinct counties or imputed values you never asked for — so demand a change log after every step, then check it. Confirm the county column now holds exactly 47 distinct values, not 45 (a wrong merge) or 49 (a missed variant). Confirm rows dropped equals the number of duplicates you were shown. Recompute one coerced GDP figure from the raw string yourself. These checks take seconds — so actually do them.

text
Now clean the data in these explicit steps. After EACH step print the row count before and after, plus a short change log of exactly what changed. Never drop or impute silently.
Step 1 — County names: standardise the 'county' column to Kenya's 47 official KNBS county names. Show me the full mapping table (raw value -> standard value) BEFORE applying it, and pause. Do not guess on ambiguous ones (e.g. 'Muranga' vs "Murang'a", 'Trans Nzoia' vs 'Trans-Nzoia') — flag them for me to decide.
Step 2 — Numerics: convert 'gdp' and 'unemployment' by stripping thousands commas and whitespace; convert 'inflation' by stripping the '%' sign. Report how many values converted cleanly and list every value that FAILED to convert.
Step 3 — Missing codes: treat -99, 999, 'n/a', 'N/A', '-', and empty strings as missing (NaN). Report the count set to missing per column. Do NOT impute.
Step 4 — Duplicates: show me every duplicate (county, year) row, then keep the most recent source and drop the rest. Report how many rows were dropped.
End with a summary table: rows in, rows out, cells converted, cells set missing, rows dropped.

Descriptive statistics, read critically

Now ask for the descriptives — count, mean, median, standard deviation, min, max, and quartiles per column, grouped by year where it helps. Two disciplines matter. First, spot-check: pick one statistic and recompute it on a slice by hand, because a leftover -99 sentinel will silently drag a mean down and a stray text row will make a column's mean vanish. Second, read the right statistic: county GDP and income are heavily right-skewed — Nairobi dwarfs Mandera — so the mean is misleading and the median plus the spread tell the honest story. If AI reports only the mean, ask for the median and the distribution too.

Charts, and the misleading ones AI makes

  • Truncated axis: a y-axis starting at 6% instead of 0% turns a trivial inflation wobble into a dramatic-looking spike — always ask where the axis starts
  • Dual axes: two series on separate y-scales can be slid until any two lines appear to move together, manufacturing a correlation that is not there
  • Mislabelled units: KES plotted as if USD, or a level plotted where you asked for year-on-year growth — check what was actually computed, not just what the title claims
  • Silent transforms: a log scale or a per-capita adjustment applied without telling you changes the whole message of the chart
  • Wrong chart for the data: a pie chart of parts that do not sum to a meaningful whole, or a smoothed trend line hiding the scatter underneath

Regression, and telling real patterns from noise

AI is genuinely good at translating a regression table into plain English: it will tell you a coefficient's sign and size, whether it is statistically significant, and what the R-squared implies. That is a real time-saver. But watch three slips. It slides from correlation to causation, writing 'a rise in mobile-money density causes GDP growth' when your specification supports no such claim. It misreads functional form, describing a log-level coefficient as if it were a simple unit change. And it treats a tiny p-value as importance, when significance is not the same as economic magnitude. Give it the model context — what is regressed on what, and why — and make it hedge causal language.

Spurious patterns and the overfit story

The more variables you let AI trawl against your outcome, the more high correlations it will find purely by chance — and it will wrap each one in a tidy, plausible story. A 0.9 correlation from a fishing expedition across 40 macro series is exactly what noise produces. Treat any 'finding' AI surfaces as a hypothesis, not a result: demand a plausible mechanism, check it holds out-of-sample or in another period, and confirm it is not driven by two outlier counties or leftover sentinels. Deciding which patterns are defensible is the economics — and it is the part you cannot delegate.

Check your understanding

You need summary statistics for a 50,000-row county expenditure file. Why does the module prefer an upload-and-run-code tool (ChatGPT Advanced Data Analysis, Claude's analysis tool, Excel Copilot) over pasting the table into a chat window?

Check your understanding

An AI chart claims county GDP 'rose 20%' from KES 80 billion to KES 100 billion. You spot-check the arithmetic. What is the actual percentage increase?

%

Check your understanding

You let an AI trawl 40 macro variables against county GDP growth and it proudly reports a 0.93 correlation between mobile-money agent density and growth, with a tidy causal story. What does the module say is the right response?

Exercise · try it first

You are handed county_econ_raw.csv: county-level GDP, inflation, and unemployment for Kenya's 47 counties across several years, stitched together from a mix of KNBS releases. It is messy — county names are inconsistent ('Nairobi', 'Nairobi City', 'NAIROBI'), GDP is text with thousands commas and the odd 'n/a', inflation is percent strings ('7.1%'), unemployment uses -99 for missing, there are duplicate county-year rows, and years appear as both 2019 and '2019/20'. Design the AI-assisted workflow from raw file to THREE defensible insights. Give the exact prompt you would use at each stage and the spot-check you would run after it. Assume a run-code tool (ChatGPT Advanced Data Analysis or Claude's analysis tool).

Stuck? Ask Mwalimu (bottom-right) to check your reasoning.

Key takeaways

  • AI that runs real code on your file (ChatGPT Advanced Data Analysis, Claude's analysis tool, Excel Copilot) is trustworthy in a way that AI merely 'reading' a pasted table is not — because you can inspect and re-run the code
  • Profile before you clean and diff before you accept: know your types, ranges, and missingness first, then check exactly what every cleaning step changed
  • AI fabricates summary numbers with total confidence — a wrong mean, a mislabelled axis, an invented correlation — so recompute every headline figure against the raw data
  • Finding a pattern is easy; AI will happily overfit a story to noise. The economic judgement is deciding which patterns are real and defensible

Further reading

  1. 01

    Tidy Data

    Hadley Wickham · Journal of Statistical Software · 2014The discipline of structuring a dataset before you analyse it — one variable per column, one observation per row.

  2. 02

    Python for Data Analysis

    Wes McKinney · O'Reilly · 2022What pandas actually does — the operations an AI data tool runs on your uploaded file.

  3. 03

    Calling Bullshit: The Art of Skepticism in a Data-Driven World

    Carl T. Bergstrom & Jevin D. West · Random House · 2020Spotting misleading charts, dubious summary numbers, and spurious correlations.

Loading progress…
LeadAfrikPublic Economics Hub