Data cleaning in Python is the step that decides whether your analysis can be trusted. Lab and test data often arrive with mixed spellings, units typed inside cells, missing readings and typing errors. In this guide you clean a small tensile test table with pandas in six steps, and every number shown is the real output of the code.

Why Lab Data Needs Cleaning
A tensile test sheet is filled by different people on different days. One writes “Steel”, another “STEEL”, a third leaves a space after the word. A load is typed as 24.1 kN with the unit inside the cell, or as n/a when the machine failed. If you calculate strength from this table without cleaning it, the numbers will be wrong or the code will stop with an error.
The table in this tutorial is generated by the code with the problems added on purpose, so you can run it anywhere. With your own project, you load your file with pd.read_csv() and use the same steps.
Step 1: Build the Messy Table and Look Before You Change Anything
import numpy as np, pandas as pd
rng = np.random.default_rng(7)
n = 40
mat = rng.choice(['Steel', 'steel ', 'STEEL', 'Aluminium', 'aluminium', 'Al'], n)
load = rng.normal(24, 3, n).round(2) # kN
area = rng.normal(78.5, 0.8, n).round(2) # mm2
elong = rng.normal(18, 2.5, n).round(1) # %
raw = pd.DataFrame({'specimen': [f'S{i:02d}' for i in range(n)],
'material': mat,
'max_load_kN': load.astype(object),
'area_mm2': area,
'elongation_pct': elong})
raw.loc[3, 'max_load_kN'] = '24.1 kN' # unit typed inside the cell
raw.loc[11, 'max_load_kN'] = 'n/a' # text where a number should be
raw.loc[17, 'area_mm2'] = np.nan # missing area
raw.loc[25, 'elongation_pct'] = np.nan # missing elongation
raw.loc[8, 'elongation_pct'] = 180.0 # typing error
raw = pd.concat([raw, raw.iloc[[5, 20]]], ignore_index=True) # 2 duplicatesAlways inspect first: shape, data types, missing values and label counts.
(42, 5)
specimen str
material str
max_load_kN object
area_mm2 float64
elongation_pct float64
area_mm2 1
elongation_pct 1
material
aluminium 11
Al 8
Aluminium 7
steel 6
STEEL 6
Steel 4Two warning signs show up at once. The load column is an object column, which means pandas found text mixed with numbers. The material column has six spellings for what is really two materials.
Step 2: Remove Duplicates and Fix Text Labels
df = raw.copy() # keep the raw table untouched
df = df.drop_duplicates()
print('after duplicates:', df.shape)
df['material'] = (df.material.str.strip().str.lower()
.replace({'al': 'aluminium'}).str.capitalize())
print(df.material.value_counts().to_dict())
after duplicates: (40, 5)
{'Aluminium': 24, 'Steel': 16}
Three string methods do most of the work: strip() removes stray spaces, lower() makes the case equal, and replace() maps a short form such as Al to the full name.
Step 3: Convert Text to Numbers
We remove the unit text and convert the column with pd.to_numeric. The option errors='coerce' turns anything that is not a number, such as n/a, into a missing value that we can handle in the next step instead of crashing the code.
df['max_load_kN'] = pd.to_numeric(
df.max_load_kN.astype(str).str.replace(' kN', '', regex=False),
errors='coerce')
print('bad loads ->', df.max_load_kN.isna().sum())
df.loc[df.elongation_pct > 60, 'elongation_pct'] = np.nan # impossible value
bad loads -> 1Step 4: Flag Impossible Values
An elongation of 180% is not possible for these specimens, so we mark values above 60% as missing. The limit comes from engineering knowledge about the material, not from a formula. Never delete a value silently. Write down what you changed and why.
Step 5: Fill Missing Values and Calculate
We fill each gap with the median of the same material, then calculate ultimate strength as load divided by area.
for col in ['area_mm2', 'max_load_kN', 'elongation_pct']:
df[col] = df[col].fillna(df.groupby('material')[col].transform('median'))
df['strength_MPa'] = (df.max_load_kN * 1000 / df.area_mm2).round(1)
print(df.isna().sum().sum(), df.shape)
print(df.groupby('material')[['strength_MPa', 'elongation_pct']]
.agg(['mean', 'std']).round(1))
print(df.describe().round(2).loc[['count', 'min', 'max']])
0 (40, 6)
strength_MPa elongation_pct
mean std mean std
material
Aluminium 303.5 39.1 17.5 2.5
Steel 295.9 32.2 17.8 2.0
max_load_kN area_mm2 elongation_pct strength_MPa
count 40.00 40.00 40.0 40.0
min 16.45 76.87 12.7 207.6
max 30.00 79.72 23.6 379.7Step 6: Check the Result
| Check | Result | What it tells you |
|---|---|---|
| Missing values left | 0 | Nothing will break the next calculation |
| Rows | 40 (was 42) | Only the 2 duplicates were removed |
| Material labels | 2 | Aluminium and steel only |
| Load range | 16.45 to 30.00 kN | Realistic for the specimen size |
| Area range | 76.87 to 79.72 mm² | Close to the 78.5 mm² target |
| Elongation range | 12.7 to 23.6% | The 180% error is gone |
These checks take two minutes and prevent most reporting mistakes. The group summary also gives you a first comparison: mean strength is 303.5 MPa for aluminium and 295.9 MPa for steel in this generated data, with a spread of about 39 and 32 MPa. Since the data is generated, do not read these as real material properties.
Cleaning Rules That Keep You Honest
| Rule | Why |
|---|---|
| Keep the raw file and clean a copy | Anyone can check what you changed |
| Record every change | Your report must say how many values were filled or removed |
| Fix the cause when you can | Re-measure a bad reading instead of guessing it |
| Fill gaps with care | Medians are fine for small gaps, not for half a column |
| Never remove values just because they look inconvenient | Outliers can be real, so check the test record first |
Where to Go Next
With a clean table you can plot it, which our pandas tutorial and guide to plotting CFD and FEA results explain. Then try a model in machine learning for beginners or linear regression in Python. For project ideas, see Python for mechanical engineers. The official pandas guide to missing data covers more options.
If you want help cleaning your own test data or explaining your cleaning steps in a report, you can reach us through the Python for mechanical engineers page.
A note on the code in this guide. It is a small learning demo that shows how the method works, using generated data. For a full project with your own data, complete analysis, code and report, we offer paid project support, where we plan the work with you and explain every step. Contact us through the Python for mechanical engineers page to discuss your topic and the cost.
FAQs
Why clean data before building a model?
A model learns from whatever you give it. Wrong labels, text in number columns and impossible values lead to wrong results, and the model will not warn you.
Should I delete rows with missing values?
Only if few rows are affected. With small lab data, deleting rows throws away real measurements. Filling with a group median is a simple, honest alternative, and you should state it in your report.
Is filling with the median always correct?
No. It is a reasonable first choice for small gaps, but a measured value is always better. If many values are missing, repeat the test or explain the limitation.
How do I find outliers?
Check the minimum and maximum of every column against physical limits, plot a histogram or box plot, and look at any value far from the rest. Decide with your engineering knowledge, not only a formula.
Do I change the original file?
Never. Keep the raw file as recorded and write the cleaned table to a new file, so every change can be checked later.
Interested in this project? Get the details, files and guidance from our team.
Enquire on WhatsApp