
Image by Author | Midjourney & Canva
When people talk about data science, they often imagine building powerful machine learning models, running predictive analytics, or making dashboards that wow the team. But the truth is, none of that matters if your data is a mess.
Before you can analyze anything, you have to make sure your data is clean, reliable, and ready for action. Think of it like cooking. Even the best recipes won’t turn out right if your ingredients are spoiled. That’s exactly what messy data does; it ruins the whole outcome.
And that’s where Pandas comes in. Pandas is the most popular Python library for working with data. It gives you powerful tools to explore, clean, and shape datasets of all kinds, from scraped CSV files to API responses and real-time streams.
In real life, raw data is rarely perfect. You’ll often deal with missing values, weird formatting, outliers that make no sense, and inconsistent text entries. If you skip over these issues, you’re likely to draw the wrong conclusions. Worse, your models could be built on faulty assumptions that fall apart when used in the real world.
This guide is here to help you fix that. We’re not just going to run through a few basic tricks. Instead, we’ll walk through real techniques used by working data analysts and scientists every day. We’ll be using a public Airbnb dataset from New York City, which contains all the kinds of issues you’d expect in a real business scenario: nulls, incorrect data types, messy strings, outliers, duplicates, and more.
By the end of this article, you’ll know how to:
- Identify the most common data problems
- Use Pandas to clean and transform your dataset step-by-step
- Automate parts of your cleaning workflow
- Get your data ready for modeling, visualization, or reporting
If you’re looking to get serious about data analysis or data science with Python, this is where it begins. Clean data isn’t just a best practice. It’s the foundation.
Loading and Previewing the Dataset
We’re going to use the Airbnb NYC 2023 public dataset, which you can find on Kaggle. It includes listings, prices, reviews, availability, and more, just the kinds of messy, real-world data you’re likely to find when working with APIs or business files.
The very first step in any data cleaning workflow is to load the dataset and get a feel for what you’re working with.
Importing Pandas and Reading the CSV
import pandas as pd
# Load the dataset
df = pd.read_csv("NYC-Airbnb-2023.csv")
# Check the shape
print(f"Dataset shape: {df.shape}")
This tells you how many rows and columns are in the dataset. Real-world data can range from a few hundred rows to millions.
Peeking at the Top Rows
df.head()
This shows the first five rows and helps you get an initial impression of what’s inside: column names, data types, and any glaring inconsistencies (like weird characters or empty cells).

Getting a peek at the top rows
First Glance Checks
Now, let’s do a few diagnostic checks to understand the structure, data types, and any potential cleaning issues.
df.info()
df.info()
This outputs:
- Number of non-null values in each column
- Data types (int64, float64, object, etc.)
- Total memory usage
You’ll often discover things like columns that should be numeric but are stored as strings or columns with many missing values.
df.describe(include=”all”)
df.describe(include="all")
This gives you:
- Summary statistics for numeric columns (count, mean, std, min, max)
- Unique counts, top values, and frequency for categorical columns
It’s great for spotting outliers, empty strings, and default placeholder values like 0 or unknown.
df.isnull().sum()
df.isnull().sum().sort_values(ascending=False)
This is your quick snapshot of missing data, sorted so that the columns with the most nulls are on top. You’ll often find columns that need imputation, dropping, or closer inspection.
Identifying and Handling Missing Data
Real-world datasets almost always have missing values, and this Airbnb NYC dataset is no exception. Let’s start by running a quick check to see which columns are missing data and how much is missing:
# Check for missing values df.isnull().sum().sort_values(ascending=False).head()
This gives us a table of columns with missing data sorted from most to least. In our case, the top culprits are:
- license: missing in over 42,000 entries
- reviews_per_month and last_review: both missing in around 10,000 entries
- name and host_name: missing in just a handful
Now, what do we do with this?
Basic Rules of Thumb
- Drop the column if it’s missing almost everything and doesn’t add useful info (like license)
- Drop rows if the column is critical and only a few rows are missing
- Fill in missing values if you can make a reasonable guess (like using 0 or the mean)
Here’s an example:
# Drop 'license' since it's mostly empty df.drop(columns=["license"], inplace=True) # Fill missing reviews_per_month with 0 df["reviews_per_month"].fillna(0, inplace=True) # Drop rows where host_name or name is missing df.dropna(subset=["host_name", "name"], inplace=True)
After applying these fixes, we should run .isnull().sum() again to confirm we’ve handled the major gaps. A simple bar plot can also help us see the missing values:
import matplotlib.pyplot as plt
missing = df.isnull().sum()
missing = missing[missing > 0]
plt.figure(figsize=(8, 4))
missing.plot(kind='barh', color='coral')
plt.title("Columns with Missing Data")
plt.xlabel("Number of Missing Values")
plt.ylabel("Column Name")
plt.tight_layout()
plt.show()

Columns with missing data
Cleaning and Standardizing Text Data
Text columns often contain inconsistencies. Host names, neighborhood names, room types, and more might be written in different cases, contain leading or trailing spaces, or even be typos.
Let’s focus on a few common text cleanup techniques:
Strip Extra Spaces and Standardize Case
df["host_name"] = df["host_name"].str.strip().str.title() df["neighbourhood_group"] = df["neighbourhood_group"].str.strip().str.title() df["room_type"] = df["room_type"].str.strip().str.title()
This ensures everything looks consistent. For example, “private room”, “Private Room “, and “PRIVATE ROOM” all become “Private Room”.
Remove Duplicate Listings (by name and host)
Sometimes the same host lists the same room more than once.
df.drop_duplicates(subset=["name", "host_id"], keep="first", inplace=True)
Quick Check: Unique Values in a Column
Let’s say you want to check for strange values in the room_type column:
df["room_type"].unique()
If something odd shows up (like “Entire home/apt ” with a trailing space), it’s a sign you need to clean that column further.
Fixing Data Types
Now that we’ve tidied up the text data, it’s time to fix some of the trickier columns, the ones that look like numbers or dates, but are actually stored as strings. This happens a lot when importing CSVs, especially if the original file has symbols, commas, or blanks.
Convert last_review to a Real datetime
We already handled this earlier by using:
df["last_review"] = pd.to_datetime(df["last_review"], errors="coerce")
This ensures we can sort or filter listings based on review dates, and also makes it easier to do time-based analysis later.
Clean and Convert Price to a Numeric Format
This column often contains dollar signs and commas. That’s fine for spreadsheets, but Python needs it in raw numeric form to do math. Let’s clean it up:
# Remove dollar signs and commas, then convert to float
df["price"] = df["price"].replace('[\$,]', '', regex=True).astype(float)
Once converted, we can now calculate things like average or median price across the city without getting errors.
Convert reviews_per_month to a Numeric Format
Sometimes, missing values or strange formatting can turn this column into an object instead of a float. Let’s make sure it’s properly typed:
df["reviews_per_month"] = pd.to_numeric(df["reviews_per_month"], errors="coerce")
The errors=”coerce” part turns any non-numeric junk into NaN, which we can clean or fill later.
Quick Type Check
After doing all of that, it’s good practice to take a quick peek at the updated data types:
df.dtypes
Detecting and Removing Outliers
Cleaning data isn’t just about fixing what’s missing or mislabeled; it’s also about removing values that just don’t make sense. In pricing data, for example, extreme values can skew your analysis and lead to wrong conclusions. You don’t want a handful of $10,000 listings messing with your average nightly rate.
Step 1: Visualize Outliers
We started by plotting a boxplot of the price column. A boxplot is a great visual tool for instantly spotting the spread of data and identifying outliers, those points that are far above or below the rest.

Visualizing the outliers
As the chart above shows, there are plenty of extreme price values that fall far outside the typical range.
Step 2: Use the IQR Method
To clean this up properly, we used the Interquartile Range (IQR) method. It works like this:
- Q1 is the 25th percentile
- Q3 is the 75th percentile
- IQR = Q3 – Q1
Any value below Q1 – 1.5 * IQR or above Q3 + 1.5 * IQR is considered an outlier.
Q1 = df["price"].quantile(0.25) Q3 = df["price"].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR # Filter the DataFrame to remove those outliers df = df[(df["price"] >= lower_bound) & (df["price"] <= upper_bound)]
Step 3: Check the Results
We removed 3,293 listings that were considered extreme outliers in terms of price.
Creating New Columns for Analysis
Sometimes, the insights you really need aren’t directly in the dataset. You have to derive them by combining or transforming existing columns. This is called feature engineering, and it's a huge part of turning raw data into actionable insights.
Let’s go over a few examples we just created:
1. Extract the Month From last_review
If you're analyzing seasonal trends, knowing the month of the last review helps you see patterns like peak travel times.
df["last_review_month"] = df["last_review"].dt.month_name()
Now you can group listings by month to see when reviews spike.
2. Price Per Review
Not all listings are created equal. Some may charge more but get fewer reviews. By dividing price by number of reviews, you can spot overpriced or undervalued listings.
df["price_per_review"] = df["price"] / (df["number_of_reviews"] + 1)
We add 1 to avoid dividing by zero; it’s a simple trick to keep things working smoothly.
3. Listing Age in Days
You might want to know how long a listing has been around. We can estimate that by subtracting the last_review date from the end of the year.
df["listing_age_days"] = (pd.Timestamp("2023-12-31") - df["last_review"]).dt.days
This gives you a rough age of each listing, which could be useful in filtering out outdated or inactive ones.
Handling Categorical Variables
Categorical data is one of the most useful types of information in a dataset. But before using it in visualizations or machine learning, we need to make sure the values are clean and consistent.
Step 1: Review the Categories
We looked into the unique values in the following columns:
- neighbourhood_group (e.g., Manhattan, Brooklyn)
- room_type (e.g., Entire home/apt, Private room)
These columns have a manageable number of unique categories, which is great; they’re clean enough for grouping and visualization.
Step 2: Normalize Inconsistent Strings
If we saw issues like “entire home/apt ” (with a trailing space) or inconsistent capitalization, we’d fix that using:
df["room_type"] = df["room_type"].str.strip().str.title() df["neighbourhood_group"] = df["neighbourhood_group"].str.strip().str.title()
We already handled this in a previous section, so we're good here.
Step 3: Encode for Machine Learning (Optional)
If you plan to feed this into a machine learning model later, you’ll need to convert these text-based categories into numeric form. The most common approach is one-hot encoding:
df_encoded = pd.get_dummies(df, columns=["room_type", "neighbourhood_group"], drop_first=True)
This adds new binary columns like room_type_Private Room or neighbourhood_group_Queens, which a model can interpret.
Saving the Cleaned Dataset
All the work we’ve done, checking for nulls, cleaning text, converting data types, removing outliers, and engineering new features, won’t mean much if we don’t save the cleaned version of our dataset.
This step lets you preserve the cleaned data so you can:
- Use it later for modeling or visualization
- Share it with teammates
- Reuse it without re-cleaning every time
Here’s the line of code that saved it all:
df.to_csv("NYC-Airbnb-2023-CLEANED.csv", index=False)
By saving it this way, you also prevent accidental changes to your original dataset. Always treat your raw data as read-only, and work off cleaned versions for analysis.
Now that we have the cleaned dataset, we can use it to create a small project and gain insights. Let's examine the top 10 most reviewed listings in New York City.
This kind of analysis helps answer questions like:
- Which listings are the most popular?
- What types of places get reviewed the most?
- Are certain titles more click-worthy?
import matplotlib.pyplot as plt
import seaborn as sns
# Set seaborn theme
sns.set_theme(style="whitegrid")
# Set figure size for clarity
plt.figure(figsize=(10, 6))
# Top 10 most-reviewed listings
top_reviews = df.sort_values("number_of_reviews", ascending=False).head(10)
# Barplot of listing names vs. number of reviews
sns.barplot(
y=top_reviews["name"],
x=top_reviews["number_of_reviews"],
palette="viridis"
)
plt.title("Top 10 Most Reviewed Listings in NYC")
plt.xlabel("Number of Reviews")
plt.ylabel("Listing Title")
plt.tight_layout()
plt.show()

Top 10 most reviewed listings in NYC
From this bar chart, we can easily spot which listings have received the most attention.
Wrapping Up
By now, you’ve seen that data cleaning is not just a checklist; it’s the backbone of good data science. No matter how advanced your models are or how sleek your dashboards look, they’re only as trustworthy as the data behind them. And in the real world, that data is almost always messy at the start.
With the help of Pandas and a solid, real-world dataset like Airbnb NYC 2023, we’ve walked through the exact steps data professionals take every day. We explored the dataset, dealt with missing values, standardized messy text, fixed incorrect data types, filtered out extreme outliers, engineered new features, and got everything ready for real analysis. These are the skills you’ll apply whether you’re cleaning survey results, user logs, sales reports, or API responses. And while it may feel tedious at first, you’ll come to see that clean data gives you a sense of control and clarity, the kind that makes your analysis powerful and your storytelling sharp.

GREAT. VERY CLEAR EXPLANATION. THANK YOU.