Data Cleansing in Python: Cleaning With Intent, Not Guesswork (Part 3)
From the publisher’s feed, collected in the ZeroLabs newsroom.
When Understanding Turns Into ActionIn Parts 1 and 2 of this series, we intentionally held back.We did not rush to fix missing values. We did not normalize columns simply because it is common practice. We did not engineer features or prepare data for models. Instead, we focused on something far more difficult and far more important: understanding the data.In Part 1, we learned how to read an unfamiliar dataset without assumptions. We examined structure, data types, missing values, categorical behavior, and hidden ordering issues. We built a mental model of what the data represents before touching it.In Part 2, we moved from structure to behavior. We explored distributions, skewness, time, seasonality, and correlation. We saw how averages hide variation, how visuals can mislead, and how correlation often lies when context is ignored.Now, and only now, are we ready to clean the data.Why Cleaning Comes Last, Not FirstData cleaning is often described as a mechanical step. Replace missing values. Remove outliers. Encode categories. Scale numbers.That framing is misleading.Cleaning is not about applying rules. It is about making decisions. Every cleaning step encodes an assumption about what the data should look like and how it should behave. When those assumptions are wrong, the analysis breaks silently.That is why cleaning without profiling is guesswork.This final part of the series is about turning everything we learned earlier into intentional, defensible cleaning choices.What This Part Is AboutIn this article, we clean the data step by step, but every action is justified by insights from Parts 1 and 2.We focus on handling time-related columns correctly, deciding when transformations are appropriate and when they are not, dealing with skewed distributions without destroying signal, encoding categorical variables without losing meaning, and deliberately leaving certain things untouched.This is not about making the data look tidy. It is about making the data fit for analysis and modeling.The Objective of Part 3By the end of this article, we should be able to clean a dataset without introducing hidden bias, explain why each cleaning step exists, avoid over-cleaning, prepare data confidently for modeling or reporting, and treat data cleaning as an engineering task rather than a cosmetic one.If Parts 1 and 2 were about learning to listen to the data, Part 3 is about responding carefully.A Final Mindset Before We BeginCleaning is irreversible.Once data is transformed, removed, or imputed, the original signal is gone. That is why professionals delay cleaning until they understand the consequences of every choice.We are now in a position to do this correctly.Step 1: Time-Aware Cleaning — Fixing Time Without Distorting MeaningTime is not just another feature. In most real-world datasets, time defines context, causality, and comparability. If time is handled incorrectly, even perfectly clean numeric data can produce misleading results.From Parts 1 and 2, we already know that time is split across year and month, month is categorical with implicit ordering, passenger behavior changes over time, and distributions and variance are not stable across years.This means time cannot be treated casually. Cleaning must respect how time behaves in the data.We convert month into a reliable numeric representation to remove ambiguity and make ordering explicit. We then construct a proper datetime column so that trends and seasonality are interpreted correctly. Finally, we explicitly sort the dataset by time to ensure chronological integrity.From Parts 1 and 2, we already learned something critical about our dataset:Time is split across year and monthmonth is categorical with implicit orderingPassenger behavior changes over timeDistributions and variance are not stable across yearsThis means we cannot treat time casually. Cleaning must respect how time behaves in the data. These steps do not change the signal. They remove risk.Step 2: Converting Month Into a Reliable Numeric RepresentationWe already identified that month is stored as abbreviated text values like Jan, Feb, Mar.Before doing anything else, we make this explicit and robust.df["month_num"] = pd.to_datetime(df["month"], format="%b").dt.monthThis step is not cosmetic. By converting month names into numbers, we remove ambiguity and make ordering explicit. This prevents silent errors in sorting, grouping, and modeling. Time-related bugs are often subtle and expensive, so clarity here matters.Step 3: Creating a Proper Datetime ColumnNow we remember something important from Part 2: trends and seasonality exist, but only make sense when time is represented correctly.Let’s construct a proper datetime column.df["date"] = pd.to_datetime( df["year"].astype(str) + "-" + df["month_num"].astype(str), format="%Y-%m")Now verify:df[["year", "month", "month_num", "date"]].head()A single datetime column simplifies everything that follows. Filtering, resampling, rolling statistics, and time-based validation all become safer and clearer. Creating this column early avoids fragile logic scattered across the codebase.Step 4: Sorting by Time ExplicitlyNever assume data is already ordered.df = df.sort_values("date").reset_index(drop=True)Sorting by time is a form of cleaning. Many algorithms and analyses silently assume chronological order. Making this explicit protects against subtle errors in rolling calculations and trend analysis later.Step 5: Removing Redundant Time Columns CarefullyNow we pause and make a decision.We currently have:yearmonthmonth_numdateDo we need all of them?The answer depends on intent.For most analytical and modeling workflows, keeping:datemonth_numis sufficient, while retaining month can help with interpretability.We will not drop anything yet.Cleaning is not about deleting aggressively. It is about preserving meaning while reducing risk. Premature column removal often forces awkward reconstruction later.Step 6: Verifying Time Integrity After CleaningBefore moving on, we confirm that time behaves as expected.df["date"].is_monotonic_increasingExpected output: TrueThis is a simple check with powerful implications. It confirms that the dataset now respects temporal order, which is essential for any downstream time-aware analysis or modeling.Step 7: A Common Mistake We Are AvoidingMany pipelines would stop here and immediately:resample datacompute rolling averagesapply forecasting modelsWe are not doing that yet.Why?Because time-aware cleaning is not complete until we account for distributional behavior and seasonality, which we identified in Part 2.Cleaning must respect behavior, not overwrite it.Step 8: Distribution-Aware Cleaning — Changing Shape Without Erasing SignalFrom Part 2, we learned that passenger counts are right-skewed and that this skewness evolves over time. Early years look very different from later years. What appears extreme in one period becomes normal in another.This immediately rules out common habits like applying global outlier thresholds, blindly normalizing the entire dataset, or forcing the data into a symmetric distribution.Not every extreme value is an outlier. In time-evolving systems, extremes are often the result of growth, not error. Removing them would erase the very signal we want to study.As a result, we keep the raw scale of passenger counts. Instead of overwriting values, we create optional derived transformations, such as a log-scaled version, to support future modeling without destroying interpretability.Cleaning does not have to be destructive.Step 9: Re-evaluating the Idea of OutliersLet’s revisit the distribution one last time, now with a cleaning mindset.df["passengers"].describe()Nothing here suggests invalid values. There are no negative counts. There are no sudden spikes that break plausibility. The high values occur in later years, where we already observed growth and higher variance.This leads to an important conclusion.Not every extreme value is an outlier. In time-evolving systems, extremes are often the result of growth, not error. Removing them would erase the very signal we want to study.As a result, we will not remove or cap passenger values. This is a conscious cleaning decision.Step 10: Deciding Whether Transformation Is NecessaryNext question.Should we transform passengers to reduce skewness?Common answers include:log transformationsquare root transformationstandard scalingBut transformations are not neutral. They change interpretability.Before doing anything, ask why.In this dataset:passenger counts are meaningful in absolute termscomparisons across time matterinterpretability is more valuable than symmetryIf a transformation improves model assumptions but destroys interpretability, it should be delayed or avoided unless absolutely necessary. Since we are not modeling yet, preserving meaning is the right choice.So for now, we keep the raw scale.Step 11: Cleaning for Stability, Not SymmetryThere is, however, one legitimate concern we identified earlier.Variance increases over time.That matters for some models, metrics, and visual comparisons.Instead of transforming the entire column, we prepare an optional derived version that can be used later if needed.df["passengers_log"] = np.log1p(df["passengers"])Creating derived columns instead of overwriting originals is a best practice. It preserves the original signal while allowing flexibility downstream. Cleaning does not have to be destructive.Step 12: Verifying That Transformation Behaves As ExpectedA quick sanity check.df[["passengers", "passengers_log"]].head()We now have:original values for interpretabilitylog-transformed values for stabilityBoth coexist without conflict.Step 13: Avoiding Over-CleaningAt this stage, it may feel like we have not done “enough.”That feeling is misleading.What we have done is:resisted unnecessary outlier removalavoided forced normalizationpreserved business meaningcreated flexibility for future modelingOver-cleaning is more dangerous than under-cleaning. It removes variance, compresses differences, and often improves metrics at the cost of truth.Clean only what you can justify.What Distribution-Aware Cleaning Gave UsAfter this step, our dataset:retains real-world variationrespects time-dependent behavioravoids artificial symmetrysupports multiple downstream pathsThis is what cleaning should do.Step 14: Categorical and Structural Cleaning — Simplifying Without Losing MeaningAt this stage, most risky decisions are behind us. What remains is structural clarity.We review the dataset and explicitly define the role of each column. The datetime column becomes the primary time reference. Numeric month values support seasonality analysis. Text month labels preserve readability. Derived features coexist with original values.We reorder columns for logical flow, validate categorical consistency one last time, and confirm that no unintended duplication has been introduced.Finally, we create a clean, analysis-ready copy of the dataset while preserving traceability to the original data.Structural cleaning is successful when every remaining column earns its place.Step 15: Reviewing What We Have After Previous StepsBefore removing or modifying anything, we look at the current structure.df.columns.tolist()At this stage, we likely have:yearmonthmonth_numdatepassengerspassengers_logThis is a good moment to pause and ask a simple but critical question.Which columns are:primary signalsderived helpersredundant representationsStep 16: Deciding What Is Redundant and WhyWe now have multiple representations of time.year and month were the original formmonth_num was added to make ordering explicitdate is the clean, canonical time representationFrom a structural standpoint:date should be treated as the primary time columnmonth_num is useful for seasonality and groupingmonth is useful for readabilityyear becomes optional once date existsWe will keep all four for now, but we explicitly define their roles.Structural cleaning does not always mean deletion. Sometimes it means declaring which column is authoritative and which ones are supporting context. Ambiguity is more dangerous than redundancy.Step 17: Reordering Columns for Logical FlowThis step does not change data, but it changes how humans interact with it.df = df[ ["date", "year", "month", "month_num", "passengers", "passengers_log"]]Column order is not cosmetic. It encodes narrative. Placing time first, followed by identifiers, then metrics, makes the dataset easier to understand and reduces cognitive load during analysis and review.Step 18: Validating Categorical Consistency One Last TimeBefore we move on, we do a final categorical sanity check.df["month"].value_counts().sort_index()We confirm:consistent spellingno unexpected labelsfull coverage of monthsThis is the last moment to catch silent category drift before modeling.Step 19: Checking for Structural Duplicates After TransformationsAny time new columns are added, it is worth confirming nothing unintended happened.df.duplicated().sum()Structural changes can sometimes introduce duplication through joins or merges. Even when no merge occurred, checking costs nothing and protects trust in the dataset.Step 20: Creating a “Ready” Dataset Without Losing TraceabilityWe now create a clean, analysis-ready version of the dataset.df_clean = df.copy()Why copy?Because:original data remains untouchedcleaning decisions are reversibleexperimentation becomes saferAlways preserve a clean boundary between raw and processed data. This is not paranoia. This is how reproducible analysis is built.Step 21: What We Did Not Remove and WhyWe did not:drop month in favor of numbers onlycollapse time into a single index prematurelyremove log-transformed or original valuesEach retained column has a purpose.Structural cleaning is successful when every remaining column earns its place.Where We Stand NowAt this point, the dataset is:time-awaredistribution-awarestructurally clearinterpretableflexible for multiple downstream usesThis is what “clean data” actually means in practice.Not minimal.Not perfectly normalized.But intentional.Final Wrap-Up: What We Did and Why It MattersIn Part 3, we finally cleaned the data. But not in the way most tutorials describe cleaning.We did not start with rules or templates. We started with understanding, and every cleaning decision followed directly from what the data had already shown us in Parts 1 and 2.We began with time-aware cleaning, because time was the backbone of this dataset. We made month ordering explicit, constructed a reliable datetime column, and enforced chronological integrity. This removed ambiguity without altering the underlying signal.Next, we moved into distribution-aware cleaning. Instead of forcing symmetry or removing so-called outliers, we respected the fact that passenger counts grow and change over time. We preserved meaningful variation, avoided destructive transformations, and created optional derived features rather than overwriting the original data.Finally, we focused on categorical and structural clarity. We reduced confusion, clarified redundancy, reordered columns for human reasoning, and created a clean, analysis-ready dataset without breaking traceability.What we ended up with is not just a cleaner dataset. It is a dataset that can be trusted.Looking Back at the Full JourneyAcross this three-part series, the progression was intentional.In Part 1, we learned how to approach an unfamiliar dataset without assumptions. We examined structure, data types, missing values, and categorical behavior. We built a mental model before touching the data.In Part 2, we studied behavior. We explored distributions, skewness, time, seasonality, and correlation. We saw how averages mislead, how visuals can deceive, and how correlation often lies when context is ignored.In Part 3, we turned understanding into action. Cleaning became an engineering process, not a guessing game. Every change had a reason. Every decision could be explained.we can conclude and say In this three-part series, we did not try to predict anything or build a model. Instead, we took a real dataset and made it safe to work with. In Part 1, we carefully examined what the data actually contains so we would not make wrong assumptions. In Part 2, we studied how the data behaves over time, how values are distributed, and why some patterns can be misleading. In Part 3, we cleaned the data only where it was necessary, keeping real patterns intact and avoiding unnecessary changes. The final result is a dataset where time is clear, values are trustworthy, and every transformation can be explained. This makes any future analysis, visualization, or modeling more reliable and much easier to do correctly.This sequence is not academic. It is how reliable data work is done in practice.Dataset Comparison: Before vs After This SeriesClean data does not mean minimal data, and it does not mean perfectly normalized tables. It certainly does not mean data that simply fits a model better. Clean data is about clarity and intent. It means that assumptions are explicit rather than hidden, transformations are applied for clear reasons rather than habit, and the structure of the dataset is easy to understand and reason about. It also means that the natural behavior of the data is respected instead of being forced into convenient shapes. When data is cleaned this way, future work becomes predictable. Models are easier to build, results are easier to explain, and unexpected surprises become far less frequent.Final ThoughtsGood data science is not about moving fast. It is about moving in the right order.Understand first.Observe behavior next.Clean with intent.Model last.If you follow this sequence consistently, your work becomes calmer, more defensible, and more trustworthy.If This Series Was HelpfulIf this series helped you think more clearly about data profiling, exploratory data analysis, or data cleaning in real-world projects, consider following me here on Medium for more practical deep dives.If you have faced similar challenges in your own work, share your experience in the comments. Real problems and thoughtful discussions are what make this community stronger.And if you found value in this series, leaving a clap or sharing it helps others discover it. Thanks !!!Thank you for reading.Data Cleansing in Python: Cleaning With Intent, Not Guesswork (Part 3) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.