Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 10/ 160
01. Python & Data Wrangling

Data Type Conversion & String Cleaning

Cast types correctly and clean messy strings with strip, replace, split, and categorical encoding prep.

Beginnerastype · str Accessors3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Turn text that should be numbers or dates into real numbers and dates, and make messy words consistent.

Think of it like…

Tidying a filing cabinet where labels are written in different handwriting: you standardise the spelling and format first so everything with the same meaning gets filed in the same folder.

Where you’ve seen it

A marketing export has spend as text ("₹1,299.50", "N/A", "1.2k"), signup_date as "03/11/26", and city as "pune", "Pune ", "PUNE". The cleaning step strips currency symbols and commas, converts with errors="coerce" to catch bad values, parses dates with an explicit format and dayfirst=True, and standardises city with .str.strip().str.title(), ending with a count of values that failed conversion for review.

Words you’ll hear

astype
Explicitly casts a column to another dtype; raises an error if values can't convert.
errors="coerce"
Turns unparseable values into NaN/NaT so you can count and inspect them.
.str accessor
Vectorised string methods on a Series of text.
category dtype
Stores repeated labels as integer codes; saves memory and speeds up grouping.

Visual diagram

Loading interactive diagram

Theory & deep dive

Safe type conversion

df["qty"].astype("int32") works only if every value converts. For messy data use pd.to_numeric(s, errors="coerce"), which converts what it can and returns NaN otherwise, then check what failed: s[pd.to_numeric(s, errors="coerce").isna() & s.notna()]. Dates: pd.to_datetime(s, format="%d/%m/%y", errors="coerce"); never rely on auto-detection with ambiguous formats, because "03/11/26" is 3 November or 11 March depending on the convention. Add utc=True or .dt.tz_localize for time zones.

Choose types for meaning, not convenience. IDs, ZIP/PIN codes and phone numbers are labels, so keep them as strings (leading zeros matter). Use nullable Int64 for integer columns with missing values, boolean for flags with NaN, and category for columns with few distinct repeated values (status, city): a 10-million-row status column can drop from hundreds of megabytes of Python strings to a few megabytes of codes. df.memory_usage(deep=True) shows the effect.

Cleaning a price column

df["price"] = pd.to_numeric(df["price"].astype(str).str.replace(r"[₹,\s]", "", regex=True), errors="coerce") then bad = df["price"].isna().sum() tells you how many values still need attention.

Key takeaway: Coerce, then inspect failures; pick types by meaning; use categories for repeats.

String cleaning with the .str accessor

The .str methods work on whole columns and skip missing values: .str.strip() removes surrounding whitespace, .str.lower() / .str.title() unify case, .str.replace("-", " ", regex=False) swaps text, .str.split(" ", expand=True) splits into columns, .str.contains("pune", case=False, na=False) filters, and .str.extract(r"(\d+)") pulls out a number with a regex group. Chain them in a readable block and keep the original column until you've verified the result.

For categorical consistency, map variants to one canonical value: df["city"] = df["city"].str.strip().str.title().replace({"Bangalore": "Bengaluru"}). Check results with df["city"].value_counts() and look for stragglers; unusual spellings often show as many categories with count 1. Invisible characters (non-breaking spaces, zero-width characters) can defeat strip(); normalise with unicodedata.normalize or a regex replace on \s and \u00a0. Finally assert your expectations: assert df["price"].dropna().ge(0).all().

Standardising a city column

df["city"] = (df["city"].str.strip().str.title().replace({"Bangalore": "Bengaluru", "Gurgaon": "Gurugram"})) then df["city"].value_counts().tail(10) to look for leftovers.

Key takeaway: Chain .str methods, map variants to canonical values, then check value counts.

How it works, step by step

Step 1 of 4
Audit

1. Inspect types and samples

Look at dtypes and sample values of every object column to see what should be numeric, date or categorical.

df.dtypes · df["spend"].sample(10)
Key numbers at this step
object
often hides issues

When to use it & trade-offs

What it is

Real files arrive with the wrong types and messy text: prices stored as "₹1,299", dates as strings, IDs as floats, categories spelled five ways. The tools are astype for explicit casts, pd.to_numeric(..., errors="coerce") and pd.to_datetime for safe parsing, the .str accessor (strip, lower, replace, split, contains, extract) for text, and category dtype for repeated labels. Cleaning means making each column the right type with consistent values, without silently inventing or losing data.

Why it matters: Wrong types break everything downstream: sorting "10" before "2", sums that concatenate strings, merges that fail because "IN " ≠ "IN", models that treat ZIP codes as numbers. Careful conversion with explicit handling of failures is routine data-science work and a frequent interview exercise.

When to reach for it

  • Parsing currency, percentage and date strings
  • Standardising city, status and category labels
  • Reducing memory with categories and smaller dtypes

When to avoid or be careful

  • Auto-detected date formats on ambiguous data
  • Storing ZIP codes or IDs as numbers
  • Coercing errors without reviewing the resulting NaNs

Conversion approaches

astype
Best for: Clean data where every value should convert

Strengths: Explicit and fast; fails loudly on bad values.

Watch out: Crashes on a single bad value.

to_numeric / to_datetime with errors="coerce"
Best for: Messy real-world columns

Strengths: Converts what it can; failures become inspectable NaN.

Watch out: Can hide problems if you don't check the NaN count.

category / nullable dtypes
Best for: Repeated labels and integer columns with gaps

Strengths: Less memory; correct semantics with missing values.

Watch out: Some operations need care with category sets.

Interview signals & numbers to know

When this topic comes up

  • “This numeric column is sorting wrongly”
  • “Dates parse as the wrong month”
  • “Clean these inconsistent labels”
  • str accessor questions
  • Memory optimisation

Benchmarks & rules of thumb

dayfirst -
common source of date errors
category -
can cut memory by 90%+ for repeated labels
Int64 -
nullable integer dtype

Common mistakes & follow-ups

Common interview mistakes

  • Converting a PIN code to int and losing a leading zero.
  • Using errors="coerce" and never looking at the NaNs it created.
  • Parsing "03/11/26" without a format and getting March instead of November.

Likely interviewer follow-ups

  • How would you convert a price column with symbols to numbers safely?
  • Why keep ZIP codes as strings?
  • When is the category dtype worth it?
Interview tip: Always count and show what failed conversion. Reporting "214 values couldn't be parsed, here are examples" turns a cleaning step into evidence.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Data Type Conversion & String Cleaning with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Duplicate Removal & Outlier Detection
Next topic
GroupBy, Aggregations & Pivot Tables