Clean Survey Data with Python for Research
An export from LimeSurvey, Qualtrics, or SoSci Survey is not yet an analyzable dataset. Anyone who wants to clean survey data with Python must decide which cases and values can be professionally justified for inclusion in the analysis. These very decisions influence means, regression models, and ultimately the validity of a bachelor's thesis, dissertation, or publication.
The technical implementation with `pandas` is usually quickly learned. The methodological justification is more demanding: Is a missing value really missing? Is an extremely short completion time an exclusion criterion? Can an unusual response be deleted as an outlier? Clean data cleaning separates technical plausibility from content evaluation and documents every step so that it remains traceable in the methods section.
Before cleaning: Back up the codebook and raw data
Never work directly in the original file. Save the unprocessed export unchanged and create a separate working copy. This makes decisions reversible and allows you to show at any time how the final analysis dataset was created if asked by supervisors, co-authors, or reviewers.
The second starting point is a codebook. It records for each variable what was measured, which response categories are allowed, how missing entries were coded, and whether items need to be reverse-coded. Especially with questionnaire exports, codes such as `-99`, `999`, empty strings, or texts like "no answer" are common. Without a codebook, these values can mistakenly be included as real measurements in descriptive statistics.
First, load the dataset and check the structure, data types, and initial values:
```python
import pandas as pd
raw = pd.read_csv("umfrage_export.csv", sep=";")
df = raw.copy()
print(df.shape)
print(df.dtypes)
print(df.head())
print(df.isna().sum())
```
The separator depends on the export format. For German CSV files, a semicolon is often correct, while decimal numbers may use a comma. Therefore, check early on whether numerical variables were actually read in as numbers and not as text. An income of `"3.500,00"` cannot be meaningfully analyzed before you have consistently converted it.
Cleaning survey data in Python: Handling missing values correctly
Missing values are not a uniform problem. An unanswered age question, an item skipped through filter logic, and a value of `99 = no answer` look different in the export but can have the same analytical meaning. Conversely, a systematically skipped item can carry content information and must not be equated with a random missing value without scrutiny.
First, standardize technical missing codes. The specific list must come from your questionnaire, not from a standard recipe:
```python
missing_codes = [-99, -9, 99, 999]
df = df.replace(missing_codes, pd.NA)
df = df.replace(["", " ", "keine Angabe", "NA"], pd.NA)
```
Afterward, you should examine the missing values per variable and per case. A high missing rate in a single item can indicate unclear wording, a programming error, or an unsuitable filter question. Many missing values across the entire questionnaire, on the other hand, can indicate a dropout.
```python
missing_per_item = df.isna().mean().sort_values(ascending=False)
missing_per_case = df.isna().mean(axis=1)
```
Whether you exclude cases or impute individual values depends on the research question, sample size, scale structure, and missingness mechanism. For example, a scale mean may be permissible for a few missing item values, provided this is methodologically justified and transparently reported. For substantial proportions of missing data, simple replacement with the overall mean is often too crude because variance and relationships can be distorted. In such cases, multiple imputations or a model that can handle missing values should be considered.
Identifying implausible cases without forcing the data to fit
Data cleaning is not an opportunity to remove unwanted results. A value must not be deleted because it disrupts the hypothesis or changes a p-value. Permissible are pre-defined or clearly factually justified criteria, such as impossible values, duplicate participation, or questionnaires that were obviously not completed seriously.
First, check the value ranges. If age was collected between 18 and 70 years, an age of 700 is highly likely to be an entry or export error:
```python
age_invalid = ~df["alter"].between(18, 70)
print(df.loc[age_invalid, ["teilnehmer_id", "alter"]])
```
Such a finding does not automatically mean the entire case must be excluded. Perhaps only one variable was incorrectly recorded and can be set as missing. Exclusion of the entire questionnaire is more plausible when several key pieces of information are contradictory or unusable.
With completion times, caution is particularly important. Very short times can indicate clicking through, but the threshold is not universal. A short, simple questionnaire is filled out faster than a long scale with vignettes. Therefore, use completion time together with other indicators: extremely low response variance, contradictory answers, failed attention checks, or identical response patterns across numerous items.
```python
Example: Mark cases under 120 seconds for review
df["kurze_dauer"] = df["dauer_sekunden"] < 120
Number of different answers across five Likert items
gruppen_items = ["item1", "item2", "item3", "item4", "item5"] df["anzahl_antwortmuster"] = df[gruppen_items].nunique(axis=1) ```Marking is better than immediate deletion. Check conspicuous cases individually or conduct sensitivity analyses: Does the central result change when clearly problematic cases are included and excluded? Especially with small samples, this transparency is more valuable than a seemingly perfect data foundation.
Check duplicates, filter logic, and response scales
Duplicate rows are not always duplicate participations. Some survey systems generate similar datasets during test runs, partial submissions, or repeated exports. First, look for a unique participant ID. If it is missing, timestamps, technical identifiers, and identical response patterns can provide clues, but must not be taken as proof prematurely.
```python
duplicates = df[df.duplicated(subset="teilnehmer_id", keep=False)]
print(duplicates.sort_values("teilnehmer_id"))
```
Also check the filter logic. If only employed people should see a question about weekly working hours, missing values for non-employed people are correct. Counting these cases as data errors would misjudge the quality of the dataset. Therefore, create a plausibility rule for each conditional question that matches the programmed filter logic.
Likert scales also deserve their own check. Check whether all items are coded in the same direction. For a five-point scale from 1 to 5, the reverse coding of a negatively phrased item is `6 - Value`:
```python
df["item3_rekodiert"] = 6 - df["item3"]
```
Only recode if the item wording requires it, and keep the original item in the dataset. This keeps the work step verifiable. Only after that should you create scale values and analyze reliabilities or factor structures.
Document the cleaning and make it reproducible
A good cleaning is evident not only in the final dataset but also in the traceable path to it. Work with a script instead of making manual changes in Excel. Every step can then be rerun, checked, and adjusted if inclusion criteria change. For research projects, this reproducibility is a quality feature, not merely a technical convenience.
Additionally, keep a cleaning log. This should include the number of exported cases, excluded test cases, duplicates, dropouts, exclusion criteria, recodings, and the final analysis sample. In the methods section, a compact description is often sufficient, while the complete script and log can remain available internally or as an appendix.
A decision flow is particularly convincing: Of how many questionnaires originally started, how many cases remained after applying defined criteria? This makes it clear that your selection was not tailored to a desired result after the fact.
When professional statistical advice is useful
For manageable, cleanly programmed surveys, the mentioned checks are often sufficient as a solid foundation. It becomes more complex with many filter paths, multiple measurement points, scales with reverse items, sensitive medical data, or high missing proportions. Then a wrong cleaning decision can affect the subsequent analysis more than the choice between two statistical tests.
Easy Statistik supports research projects with traceable Python workflows, methodologically justified inclusion criteria, and clear documentation for a thesis or publication. If in doubt, use the contact form for a discreet initial assessment by PhD statisticians. The most sensible next step is not to delete as many cases as possible, but to professionally justify every data decision so that you can defend your result with good reason.