Introduction to Data Wrangling

What data wrangling is and why it takes so much of an analysis. The term's origin in database research, the steps of exploring, structuring, cleaning, enriching, validating and publishing, how wrangling differs from extract-transform-load pipelines, and the core pandas operations for reading and inspecting a table, followed through one complete wrangle of two public NHANES files from raw records to mean blood pressure by age, with the rows kept at every step.

Data wrangling is the work between receiving data and analyzing it, in six steps: explore, structure, clean, enrich, validate and publish. It is the ad hoc counterpart of an extract-transform-load (ETL) pipeline: one analyst and one question, not a scheduled job. The often-quoted 80% share of an analysis is an estimate, not a measurement. A complete wrangle of two public NHANES 2017 to 2018 files leaves 5,247 of the 9,254 people interviewed as adults with a systolic reading. Their mean systolic pressure rises from 114.8 mm Hg at ages 18 to 39 to 136.8 at 60 and over (126.4 overall, unweighted; 123.4 with the survey weights). Averaging diastolic zeros in as pressures would lower the diastolic mean from 72.49 to 72.12 mm Hg.

The National Health and Nutrition Examination Survey (NHANES) publishes its 2017 to 2018 results as dozens of separate files. One of them, DEMO_J, has a row for each of the 9,254 people interviewed, with their age, sex, household and income. Another, BPX_J, has a row for each of the 8,704 people who then attended the physical examination, with up to three systolic and three diastolic blood pressure readings. Suppose the question is simple: what is the average blood pressure of adults, by age group? Neither file answers it. The ages are in one file and the pressures in the other. Every column, including the person identifier and the codes for sex, arrives as a floating-point number. Some diastolic readings are 0. Children are mixed in with adults, and some people who came to the examination have no reading at all. Once those problems are dealt with, the answer is the rise in mean systolic pressure with age given above.

Getting from those files to a table that answers the question is data wrangling: the work between receiving data and analyzing it. This article defines it, lays out its usual steps, contrasts it with the automated pipelines of data engineering, introduces the pandas operations used to read and inspect data, and then carries the NHANES question through every step, counting the rows that survive each one. The later articles of this topic take the steps one at a time: Exploring Data with Groups and Pivot Tables, Structuring Data, Cleaning Data, Enriching Data and Data Engineering.

What wrangling is

Database and visualization research gave the term a working definition. Kandel, Paepcke, Hellerstein and Heer (2011) describe data wrangling as work that "regularly involves reformatting data values or layout, correcting erroneous or missing values, and integrating multiple data sources", and note that analysts often do it by "writing idiosyncratic scripts in programming languages such as Python and Perl, or extensive manual editing using interactive tools such as Microsoft Excel". The same activity goes by other names, among them data munging, data cleaning and data preparation; Wickham (2014) uses "data cleaning" for the whole of it and "tidying" for one part, the arrangement of values into rows and columns.

How much of an analysis it takes is often quoted and rarely measured. Wickham (2014) opens with "It is often said that 80% of data analysis is spent on the process of cleaning and preparing the data", citing Dasu and Johnson (2003), and Kandel et al. (2011) cite an estimate that data cleaning accounts for up to 80% of the development time and cost in data warehousing projects. These are estimates, not measurements, and the share varies with the project. The interview study of Kandel, Paepcke, Hellerstein and Heer (2012) gives a more direct impression. Having interviewed 35 analysts from 25 organizations, the authors describe discovery and wrangling as "often the most tedious and time-consuming aspects of an analysis", and one analyst told them, "I spend more than half of my time integrating, cleansing and transforming data without doing any actual analysis." The safe statement is that wrangling regularly takes a large part of an analysis, often more than the modeling.

It matters for a reason beyond time. Every number an analysis reports depends on decisions made during wrangling: which rows were kept, what a code was taken to mean, how two files were matched. Those decisions are rarely visible in the final result, which is why they deserve to be written down and checked.

The steps

A common way to organize the work, used for this topic, has six steps. The order is logical rather than strict; in practice each step can send the analyst back to an earlier one.

  1. Explore. Find out what the data contain before changing anything: the number of rows and columns, their types, the range of each variable, how much is missing, what the codes mean. Summaries by group are part of this step (Exploring Data with Groups and Pivot Tables).
  2. Structure. Arrange the data so that each variable is a column and each observation a row, give each column the right type, put dates, units and category labels into one consistent form, and rescale numerical features where a method needs it (Structuring Data).
  3. Clean. Find and handle missing values, special codes, impossible values, duplicates and inconsistencies, with a stated reason for each decision (Cleaning Data).
  4. Enrich. Add information: join other tables, stack further records, derive new variables from existing ones (Enriching Data).
  5. Validate. Check that the result obeys rules it must obey: keys are unique, values lie in their documented ranges, totals agree with published totals, related values are consistent.
  6. Publish. Save the result, with a record of how it was made, where others (including the analyst's future self) can use it.

Kandel et al. (2012) offer a related division of an analysis into five tasks, discovery, wrangling, profiling, modeling and reporting, in which "profiling" is the checking of data quality that the list above calls exploring and validating. The names differ; the work is the same.

Wrangling and ETL

Organizations that analyze data routinely build pipelines that do much of this work automatically. The classic form is extract, transform, load (ETL): extract data from the operational systems that record day-to-day transactions, transform it into consistent, cleaned tables, and load it into a database designed for analysis, the data warehouse. Chaudhuri and Dayal (1997), in an early survey of data warehousing, describe its back end as tools "for extracting, cleaning and loading data into a data warehouse". A pipeline runs on a schedule, on the same sources each time, and is maintained as software. A variant, ELT, loads the raw data first and transforms it inside the analytical database.

Wrangling, in the sense of this topic, is usually the ad hoc counterpart: one analyst, one question, a dataset that may never be processed again. The two are layers rather than rivals. An analyst often wrangles data that a pipeline has already loaded into a warehouse, because the warehouse was built for questions other than the one at hand. Data Engineering covers pipelines, warehouses and the file formats they use.

Reading and inspecting data in pandas

pandas, the standard Python library for tables, represents a table as a DataFrame: labeled columns, each with one data type, and a row index. The pandas article of the Python topic introduces it; the operations below are the ones a first look at data needs.

Reading. Each format has its own reader, and each returns a DataFrame:

import pandas as pd

demo = pd.read_csv("demographics.csv")              # comma-separated text
ws = pd.read_excel("workbook.xlsx", sheet_name=0)   # a spreadsheet (needs openpyxl)
bpx = pd.read_sas("BPX_J.xpt", format="xport")      # a SAS transport file, as NHANES publishes
tbl = pd.read_sql("select * from visits", con)      # the result of a SQL query

The NHANES files are SAS transport (XPORT) files. pandas reads them, but its reader returns a stored zero as a tiny positive number, about $5.4 \times 10^{-79}$, rather than 0. That was checked on 23 November 2026 with pandas 2.2.3 and with 3.1.1, the current release; a fix is merged for pandas 3.2. Cleaning Data explains why it happens and how this site's scripts restore the zeros. The code in this article reads the files through that corrected reader. Reading from a database through SQL is covered in Queries in Python.

Inspecting. df.shape gives the numbers of rows and columns, df.head() the first rows, df.dtypes the type of each column and df.info() all of these with the count of non-missing values in each column. For four columns of BPX_J:

 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   SEQN    8704 non-null   float64
 1   BPXSY1  6302 non-null   float64
 2   BPXDI1  6302 non-null   float64
 3   BPXSY2  6563 non-null   float64

This is already informative. The first systolic reading is present for 6,302 of the 8,704 people examined, the second for 6,563: the second reading is more often present than the first. And every column, including the person number SEQN (93703, 93704, ...), is stored as float64. That is a property of the file format, which stores every number as a floating-point value; the DEMO_J file has all 46 of its columns in the same type. A person number is an identifier and a sex code is a category, and Structuring Data converts both.

Summarizing and sorting. df.describe() gives the count, mean, standard deviation, quartiles and extremes of each numerical column, and s.value_counts() the frequency of each value of a column s. Sorting by a column with df.sort_values("BPXDI1") and looking at both ends is a quick way to find impossible or suspicious values. In BPX_J, the lowest first diastolic readings are 0 and the highest is 136, while first systolic readings run from 72 to 228 mm Hg. A diastolic pressure of 0 is not a physiological value, so the documentation must be consulted, and it says that "Diastolic BP can be zero" (National Center for Health Statistics, 2020a). The examination manual implies how such a value arises: the examiner listens through a stethoscope as the cuff deflates and records as the diastolic pressure "the point at which the last muffled sound is heard" (National Center for Health Statistics, 2018, §3.1.3.8). A reading of 0 therefore means that the sounds were still audible when the cuff pressure reached zero, so no diastolic value was found. For an average, 0 is best treated as missing, because it is not a pressure. The manual's own averaging rule differs: it sets a person's diastolic average to 0 when every reading is 0 (National Center for Health Statistics, 2018, §3.1.4.3).

Selecting. df.loc[rows, columns] selects by label (including Boolean conditions such as df.loc[df.RIDAGEYR >= 18]), df.iloc by position and df.at[row, column] a single value. Selecting the rows a question is about is often the first real decision of a wrangle, as the next section shows.

One wrangle from start to finish

The question: the mean systolic and diastolic blood pressure of adults aged 18 and over, by age group, among the people examined in NHANES 2017 to 2018. Each step below is a few lines of pandas; the decisions are the substance.

Rows remaining after each step of the wrangle. The join keeps all 9,254 interviewed people, 550 of whom were not examined; restricting to adults, to the examined and to those with a systolic reading leaves 5,247, and treating diastolic zeros as missing leaves 5,232 with a usable diastolic pressure.
Rows remaining after each step of the wrangle. The join keeps all 9,254 interviewed people, 550 of whom were not examined; restricting to adults, to the examined and to those with a systolic reading leaves 5,247, and treating diastolic zeros as missing leaves 5,232 with a usable diastolic pressure.

Explore. DEMO_J has 9,254 rows and 46 columns, BPX_J 8,704 rows and 21 columns. The person number SEQN is unique in both. The interview status variable RIDSTATR is 2 ("both interviewed and MEC examined") for 8,704 people and 1 ("interviewed only") for 550, which matches the size of BPX_J (National Center for Health Statistics, 2020b).

Enrich: join the files. A join on SEQN combines the two:

m = demo.merge(bpx, on="SEQN", how="left", validate="one_to_one", indicator=True)
m["_merge"].value_counts()      # both 8704, left_only 550, right_only 0

validate="one_to_one" makes pandas raise an error if SEQN were repeated in either file, and indicator=True adds a column saying where each row came from. All 8,704 examination records found a match, and the 550 unmatched interview records are exactly the people with status 1. A join whose counts match what the documentation predicts is a good sign; Enriching Data shows joins whose counts do not.

Clean: select the population. The question is about adults. Of the 9,254 people, 5,856 are 18 or over; 5,533 of them were examined; and 286 of those have no systolic reading at all, leaving 5,247. Each systolic value used is the mean of a person's available readings (one, two or three). The examination manual averages differently: it excludes the first reading whenever a later one exists, and records a diastolic average of 0 when every diastolic reading is 0 (National Center for Health Statistics, 2018, §3.1.4.3). This wrangle keeps the first reading, so that every adult's measurements count, and treats an all-zero record as missing, because 0 is not a pressure; Structuring Data measures how much the first reading runs high. Of the diastolic readings of these adults, 83 are zeros, spread over 53 people, and 15 people have no diastolic reading other than zeros; treating zeros as missing leaves 5,232 with a usable diastolic pressure.

Two details deserve a sentence each. First, the order of these filters does not change the result, because each one keeps the rows that satisfy its own condition and the rows kept by all three are the same whatever the order (the script checks this). Recording the count after each one is what makes the result checkable, here and in the figure above. Second, leaving out the age filter changes the answer: the 6,714 people with any systolic reading include children from age 8, and their mean systolic pressure is 121.7 mm Hg instead of 126.4. A wrangle is shaped by its question.

Validate. The blood pressure documentation lists editing rules: the systolic pressure must exceed the diastolic, and there can be no diastolic reading without a systolic one (National Center for Health Statistics, 2020a). Checking them costs a line each, and in these data neither is broken by any of the three pairs of readings. The documentation also says that systolic and diastolic readings "can be even numbers only", and all systolic readings are indeed even, a fact Types of Numerical Data uses.

Result. Grouping by age and averaging gives:

Age group Adults Mean systolic (mm Hg) Mean diastolic (mm Hg)
18 to 39 1,745 114.8 69.8
40 to 59 1,579 126.3 77.4
60 and over 1,923 136.8 70.9
All adults 5,247 126.4 72.5

Systolic pressure rises steadily with age, while diastolic pressure rises into middle age and then falls. The decision about zeros matters for the diastolic means: averaging the zeros in as if they were measurements gives an overall mean of 72.12 mm Hg instead of 72.49. That is a small shift, but it is a bias, not noise, and it would grow in any subgroup where zeros are common. These means describe the examined adults as a group of people. They are not estimates for the United States population, which would need the survey's sampling weights, as the Applied Statistics pages note when they use the same adults (Confidence Intervals and Coverage treats these 5,247 person means as a complete population from which to draw samples); Survey Weights and the Horvitz–Thompson Estimator explains the weights, and the first worked problem below applies them.

Publish. The script that produced every number above, tools/experiments/data-science/introduction-to-data-wrangling.py in the site's repository, downloads the two public files, checks that they are byte-for-byte the files it was written for, and reruns every step. That is the publishing step in its simplest form.

Wrangling as code

The steps above could have been done by hand in a spreadsheet: copy the ages next to the pressures, delete the children, blank out the zeros. Kandel et al. (2011) observed analysts doing exactly that and designed their Wrangler tool to produce "robust, auditable transforms instead of manual editing". The argument for writing the wrangle as code, or as a recorded series of transforms, is that it can be read, checked and rerun. When the agency releases a corrected file, the script runs again; when a reviewer asks why 286 adults are missing, the line that removed them answers.

Wilson et al. (2017), in a set of practices for scientific computing, put the data rules first: "Save the raw data", record all the steps used to process data, and give every record a unique identifier. Their reason for keeping raw files untouched is that "faithful retention is essential for rerunning analyses from start to finish, for recovery from analytical mishaps, and for experimenting without fear". A wrangle that overwrites its input cannot be repeated.

Judgment in every step

Wrangling is not a sequence of mechanical fixes. The zero diastolic readings were not errors to delete; they were a documented recording convention, and the right treatment depended on the question (an average) rather than on the data alone. The 286 adults without a systolic reading could have been ignored, but Cleaning Data shows they are not a random subset: they are more often in the youngest and oldest age groups, which matters for some questions more than others. The same raw files, wrangled for a different question, such as how often the examination failed to produce a reading, would keep exactly the rows this wrangle removed.

Worked problems

The numbers below are computed and checked by the review block of tools/experiments/data-science/introduction-to-data-wrangling.py, which runs unchanged under pandas 2.2.3 and 3.1.1.

Problem 1 (what the sampling weights change). Every examined NHANES participant carries an examination weight, WTMEC2YR in DEMO_J: roughly, the number of people in the United States civilian population that the participant stands for. Recompute the result table with these weights, and explain why the answer moves.

Approach. Within each age group the weighted mean is $\sum_i w_i y_i / \sum_i w_i$, the Hájek estimator that Survey Weights and the Horvitz–Thompson Estimator derives. All 5,247 adults have a positive weight, and together their weights sum to 236.7 million.

Result. The weighted mean systolic pressure of all adults is 123.4 mm Hg, against 126.4 unweighted; the diastolic mean barely moves (72.4 against 72.5). By age group the weighted systolic means are 115.1, 124.1 and 133.6, and the diastolic means 70.2, 76.8 and 70.3.

Why it moves. The examined adults are not a miniature of the population. Adults aged 60 and over are 36.6% of the 5,247 but carry 28.4% of the weight, while adults aged 18 to 39 are 33.3% of the sample and 38.0% of the weight. The overall mean is the weight-share average of the three group means, so moving weight from the oldest group, whose pressure is highest, to the youngest lowers it. How much of the 3.0 mm Hg drop is composition alone can be measured by keeping the unweighted group means and changing only the shares: that gives 124.95, so about half of the drop comes from the age mix across the three bands. The rest comes from reweighting within each band; the largest change is in the oldest band, from 136.8 to 133.6.

What this does not settle. The weights were built for everyone examined. Dropping the 286 adults without a reading and reweighting the others assumes that those 286 resemble examined adults of similar weight, an assumption Cleaning Data puts in doubt. And a standard error for 123.4 needs the survey's strata and clusters, which a weighted mean alone does not use.

Problem 2 (the mean of person means against the mean of all readings). The wrangle first averaged each adult's readings and then averaged the adults. Averaging all 15,146 systolic readings directly gives a different answer. Find it, and say which one the question asks for.

Result. The mean of the 15,146 readings is 126.01 mm Hg; the mean of the 5,247 person means is 126.36.

Derivation. Write $k_i$ for the number of readings of adult $i$ (1, 2 or 3), $m_i$ for that adult's mean, $n$ for the number of adults and $K = \sum_i k_i$ for the number of readings. The pooled mean is $\sum_i k_i m_i / K$ and the mean of person means is $\sum_i m_i / n$. Their difference is

$$\frac{1}{K}\sum_i k_i m_i - \frac{1}{n}\sum_i m_i = \frac{1}{K}\sum_i \left(k_i - \bar{k}\right) m_i, \qquad \bar{k} = \frac{K}{n},$$

since $K/n \cdot \sum_i m_i = \sum_i \bar{k}\, m_i$. The difference is zero exactly when the number of readings has zero sample covariance with the person means, and small when the two are unrelated; here they are related. The 4,730 adults with three readings average 125.37 mm Hg, while the 439 with two average 135.55 and the 78 with one 134.82. Pooling counts each three-reading adult three times, so it leans toward the group with lower pressure.

Which one. The question is about adults, so each adult should count once, and the person mean is the right unit. A question about measurements, such as how variable a single reading is, would pool the readings instead.

Open questions

  • Are the 286 adults without a reading missing at random given age and sex? NHANES 2017 to 2018 also measured blood pressure with an oscillometric device, published separately as BPXO_J. Comparing the oscillometric readings of those 286 adults with those of adults of the same age and sex who have auscultatory readings would test whether the missing auscultatory values are higher or lower than the rest.
  • How much do the weighted means of Problem 1 change when the weights are adjusted for the 286 nonrespondents? Reweighting within age and sex cells so that respondents carry the weight of the nonrespondents in their cell (the nonresponse adjustment within cells described in Survey Weights and the Horvitz–Thompson Estimator), and recomputing the table, would show whether the simple dropping matters at this scale.
  • What share of an analysis is wrangling, measured rather than estimated? The 80% figure in the literature is an estimate. A study that logs analysts' activity during real projects, classifying each step as wrangling or modeling, would settle it for the settings it covers.

Where it leads

The wrangle above made decisions of five kinds, and each later article of the unit takes one kind in turn. Exploring Data with Groups and Pivot Tables builds the grouped summaries that exploring relies on and shows how a comparison between groups can reverse when they differ in age. Structuring Data puts the readings into tidy form and fixes types, dates and scales. Cleaning Data handles special codes, the transport-file zeros and missing values, with an experiment on the common remedies. Enriching Data checks joins like the one above and adds data from other agencies. Data Engineering covers the formats, pipelines and hashes that make the publishing step repeatable.

References

Reviewed: verified, 23 Nov 2026 · citations checked, 23 Nov 2026 · editorial review, 23 Nov 2026 · 6 revisions