Python ile Veri Temizleme: Pratik İpuçları
Gerçek hayattan örneklerle, dağınık verileri temizlemek için kullandığım pratik yöntemleri açıklıyorum.
- Araçlar

Veri analizi projelerinde çoğu zaman en çok vakit alan bölüm analiz yapmak değil, analize başlamadan önce veriyi kullanılabilir hale getirmektir. Eksik değerler, duplicate kayıtlar, yanlış veri tipleri, tutarsız kategoriler ve hatalı tarih formatları sonuçların tamamını etkileyebilir.
Python ve özellikle pandas bu süreçte oldukça güçlü araçlar sunuyor. Benim için veri temizleme; tek seferlik bir işlemden çok, analizin güvenilirliğini oluşturan temel aşamalardan biri.
“İyi analiz, temiz veriyle başlar. Temiz veri ise sadece boş hücreleri silmekten ibaret değildir.”
Veri Temizleme Nedir?
Veri temizleme; bir veri setindeki hatalı, eksik, tutarsız, tekrar eden veya analiz açısından sorun yaratabilecek kayıtların tespit edilmesi ve uygun yöntemlerle düzenlenmesi sürecidir.
- Veriyi
İncele - Sorunları
Bul - Temizle
- Kontrol Et
- Analize Geç
1. İlk Adım: Veriyi Tanımak
Temizleme işlemine doğrudan başlamak yerine önce veri setinin yapısını anlamak çok daha sağlıklı. Satır sayısı, sütun tipleri, eksik değerler ve örnek kayıtlar ilk kontrol edilmesi gereken noktalar.
import pandas as pd
df = pd.read_csv("satislar.csv")
print(df.shape)
print(df.head())
df.info()
print(df.isna().sum())Boyut
Kaç satır ve kaç sütun olduğunu hızlıca görmenizi sağlar.
İlk kayıtlar
Verinin gerçek yapısını örnek birkaç satır üzerinden kontrol eder.
Veri tipleri
Sütunların tiplerini ve doluluk durumunu gösterir.
Eksik değerler
Hangi sütunda ne kadar eksik veri bulunduğunu gösterir.
2. Eksik Verilerle Çalışmak
Eksik veri gördüğümüzde ilk refleks bütün satırları silmek olmamalı. Eksikliğin neden oluştuğunu ve ilgili değişkenin analiz için ne kadar kritik olduğunu anlamak gerekir.
# Her sütundaki eksik değer sayısı
df.isna().sum()
# Eksik kayıtları kaldırmak
df_temiz = df.dropna()
# Sayısal bir alanı medyan ile doldurmak
df["yas"] = df["yas"].fillna(df["yas"].median())3. Duplicate Kayıtları Bulmak
Aynı kaydın birden fazla kez gelmesi özellikle veri farklı kaynaklardan birleştirildiğinde sık karşılaşılan bir problemdir.
# Tekrarlanan satırları say
df.duplicated().sum()
# Tekrarlanan kayıtları görüntüle
df[df.duplicated()]
# Duplicate kayıtları kaldır
df = df.drop_duplicates()4. Veri Tiplerini Düzeltmek
Bir sütunda tarihlerin metin olarak gelmesi veya sayısal bir alanın string olarak tutulması analiz sırasında sorun çıkarabilir. Bu yüzden veri tiplerini kontrol etmek önemli.
# Tarih
df["tarih"] = pd.to_datetime(df["tarih"], errors="coerce")
# Sayısal değer
df["satis"] = pd.to_numeric(df["satis"], errors="coerce")
# Kategori
df["kategori"] = df["kategori"].astype("category")5. Metinleri Standartlaştırmak
“İstanbul”, “istanbul”, “ISTANBUL ” ve “İSTANBUL” gibi değerler kullanıcı açısından aynı olabilir ama veri açısından farklı değerlerdir. Bu nedenle metin normalizasyonu özellikle kategori alanlarında oldukça önemlidir.
df["sehir"] = (
df["sehir"]
.astype("string")
.str.strip()
.str.lower()
)| Ham değer | Temizlenmiş değer |
|---|---|
| İstanbul | istanbul |
| ISTANBUL | istanbul |
| istanbul | istanbul |
6. Aykırı Değerleri Kontrol Etmek
Her sıra dışı değer hatalı değildir. Ancak özellikle gelir, satış, yaş veya süre gibi sayısal değişkenlerde aykırı değerleri kontrol etmek analiz kalitesini artırabilir.
Q1 = df["satis"].quantile(0.25)
Q3 = df["satis"].quantile(0.75)
IQR = Q3 - Q1
alt = Q1 - 1.5 * IQR
ust = Q3 + 1.5 * IQR
aykiri = df[(df["satis"] < alt) | (df["satis"] > ust)]7. Gereksiz Sütunları Kaldırmak
# Kullanılmayan sütunları kaldır
df = df.drop(columns=["gereksiz_1", "gereksiz_2"])
# Sadece ihtiyaç duyulan sütunları seç
df = df[["tarih", "kategori", "satis"]]8. Koşullu Veri Temizleme
Bazen veriyi doğrudan silmek yerine belirli kurallara göre sınıflandırmak gerekir.
# Negatif satışları işaretle
df["gecerli_mi"] = df["satis"] >= 0
# Sadece geçerli kayıtları tut
df = df[df["gecerli_mi"]]
# Yardımcı sütunu kaldır
df = df.drop(columns=["gecerli_mi"])9. Temizlik Sonrası Kontrol
Veriyi temizledikten sonra işlemin gerçekten istediğimiz sonucu ürettiğini tekrar kontrol etmek gerekiyor. Temizleme adımı, kontrol adımı olmadan tamamlanmış sayılmaz.
10. Gerçek Bir Temizleme Akışı
Pratikte tek tek kod çalıştırmak yerine temizleme adımlarını bir fonksiyonda toplamak işleri daha düzenli hale getirir.
def veri_temizle(df):
df = df.copy()
df = df.drop_duplicates()
df["tarih"] = pd.to_datetime(
df["tarih"],
errors="coerce"
)
df["satis"] = pd.to_numeric(
df["satis"],
errors="coerce"
)
df["kategori"] = (
df["kategori"]
.astype("string")
.str.strip()
.str.lower()
)
df = df.dropna(subset=["tarih", "satis"])
return dfVeri Temizlemede En Çok Yapılan Hatalar
| Hata | Neden problem? | Daha iyi yaklaşım |
|---|---|---|
| Eksik verilerin tamamını silmek | Gereksiz veri kaybına yol açabilir. | Eksikliğin nedenini ve değişkenin önemini incelemek. |
| Aykırı değerleri otomatik silmek | Gerçek önemli olaylar kaybolabilir. | Önce kaynağını kontrol etmek. |
| Ham verinin üzerine yazmak | Geri dönüş zorlaşır. | Ham ve temiz veri setlerini ayırmak. |
| Kontrol yapmamak | Temizleme sırasında yeni hata oluşabilir. | İşlem sonrası kalite kontrolü yapmak. |
Sonuç
Python ile veri temizleme, pandas'ın birkaç fonksiyonunu ezberlemekten çok daha fazlası. Asıl önemli olan verinin yapısını anlamak, hangi problemlerin gerçekten hata olduğunu ayırt etmek ve her müdahaleden sonra sonucu kontrol etmek.
Benim için iyi bir veri temizleme süreci şu sırayı takip ediyor: incele → problem çıkar → temizle → doğrula → dokümante et. Bu yaklaşım, sonraki analizlerin daha güvenilir ve daha tekrarlanabilir olmasını sağlıyor.
“Veri temizleme analizden önce yapılan bir angarya değil; doğru analizin temelidir.”
In data analysis projects, the most time-consuming part is often not the analysis itself but making the data usable before the analysis starts. Missing values, duplicate records, wrong data types, inconsistent categories and incorrect date formats can affect every result.
Python, and especially pandas, offers very powerful tools for this process. For me, data cleaning is not a one-off task but one of the core stages that make an analysis trustworthy.
“Good analysis starts with clean data. And clean data is about much more than deleting empty cells.”
What Is Data Cleaning?
Data cleaning is the process of detecting records in a data set that are wrong, missing, inconsistent, duplicated or otherwise problematic for analysis, and fixing them with suitable methods.
- Inspect
the Data - Find
Problems - Clean
- Check
- Start
Analysis
1. First Step: Getting to Know the Data
Rather than jumping straight into cleaning, it is much healthier to first understand the structure of the data set. The number of rows, column types, missing values and sample records are the first things to check.
import pandas as pd
df = pd.read_csv("sales.csv")
print(df.shape)
print(df.head())
df.info()
print(df.isna().sum())Size
Shows quickly how many rows and columns there are.
First records
Checks the real structure of the data through a few sample rows.
Data types
Shows column types and how many values are filled in.
Missing values
Shows how much data is missing in each column.
2. Working with Missing Data
When we see missing data, our first reflex should not be to delete every row. We need to understand why the data is missing and how critical the variable is for the analysis.
# Number of missing values in each column
df.isna().sum()
# Remove records with missing values
df_clean = df.dropna()
# Fill a numeric field with the median
df["age"] = df["age"].fillna(df["age"].median())3. Finding Duplicate Records
The same record arriving more than once is a common problem, especially when data is merged from different sources.
# Count duplicated rows
df.duplicated().sum()
# View duplicated records
df[df.duplicated()]
# Remove duplicate records
df = df.drop_duplicates()4. Fixing Data Types
Dates arriving as text or a numeric field stored as strings can cause problems during analysis. That is why checking data types is important.
# Date
df["date"] = pd.to_datetime(df["date"], errors="coerce")
# Numeric value
df["sales"] = pd.to_numeric(df["sales"], errors="coerce")
# Category
df["category"] = df["category"].astype("category")5. Standardizing Text
Values like “İstanbul”, “istanbul”, “ISTANBUL ” and “İSTANBUL” may mean the same thing to a person but are different values in the data. That is why text normalization is very important, especially in category fields.
df["city"] = (
df["city"]
.astype("string")
.str.strip()
.str.lower()
)| Raw value | Cleaned value |
|---|---|
| İstanbul | istanbul |
| ISTANBUL | istanbul |
| istanbul | istanbul |
6. Checking Outliers
Not every unusual value is an error. But checking for outliers, especially in numeric variables such as income, sales, age or duration, can improve the quality of the analysis.
Q1 = df["sales"].quantile(0.25)
Q3 = df["sales"].quantile(0.75)
IQR = Q3 - Q1
lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR
outliers = df[(df["sales"] < lower) | (df["sales"] > upper)]7. Removing Unnecessary Columns
# Remove unused columns
df = df.drop(columns=["unused_1", "unused_2"])
# Keep only the columns you need
df = df[["date", "category", "sales"]]8. Conditional Data Cleaning
Sometimes, instead of deleting data directly, you need to classify it according to certain rules.
# Flag negative sales
df["is_valid"] = df["sales"] >= 0
# Keep only valid records
df = df[df["is_valid"]]
# Remove the helper column
df = df.drop(columns=["is_valid"])9. Checking After Cleaning
After cleaning the data, we need to check again that the process really produced the result we wanted. A cleaning step is not complete without a checking step.
10. A Real Cleaning Workflow
In practice, collecting the cleaning steps in a function is tidier than running each piece of code separately.
def clean_data(df):
df = df.copy()
df = df.drop_duplicates()
df["date"] = pd.to_datetime(
df["date"],
errors="coerce"
)
df["sales"] = pd.to_numeric(
df["sales"],
errors="coerce"
)
df["category"] = (
df["category"]
.astype("string")
.str.strip()
.str.lower()
)
df = df.dropna(subset=["date", "sales"])
return dfThe Most Common Data Cleaning Mistakes
| Mistake | Why is it a problem? | Better approach |
|---|---|---|
| Deleting all missing data | It can cause unnecessary data loss. | Examine why data is missing and how important the variable is. |
| Automatically deleting outliers | Real, important events can be lost. | Check where they come from first. |
| Overwriting the raw data | It becomes hard to go back. | Keep raw and clean data sets separate. |
| Not checking | New errors can appear during cleaning. | Run a quality check after the process. |
Conclusion
Cleaning data with Python is much more than memorizing a few pandas functions. What really matters is understanding the structure of the data, telling which problems are real errors and checking the result after every change.
For me, a good data cleaning process follows this order: inspect → identify problems → clean → validate → document. This approach makes the analyses that follow more reliable and more reproducible.
“Data cleaning is not a chore before the analysis; it is the foundation of a correct analysis.”