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.

Temel veri temizleme akışı
  1. Veriyi
    İncele
  2. Sorunları
    Bul
  3. Temizle
  4. Kontrol Et
  5. 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.

Pandas ile ilk kontrol
import pandas as pd

df = pd.read_csv("satislar.csv")

print(df.shape)
print(df.head())
df.info()
print(df.isna().sum())
shape

Boyut

Kaç satır ve kaç sütun olduğunu hızlıca görmenizi sağlar.

head()

İlk kayıtlar

Verinin gerçek yapısını örnek birkaç satır üzerinden kontrol eder.

info()

Veri tipleri

Sütunların tiplerini ve doluluk durumunu gösterir.

isna()

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.

Eksik veri kontrolü
# 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())
Önemli: Eksik değerleri nasıl ele alacağınız, veri setinin yapısına ve analiz amacına göre değişir. Bir satırı silmek ile değeri tahmin ederek doldurmak aynı analitik sonucu üretmez.

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.

Duplicate kontrolü
# 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.

Yaygın veri tipi dönüşümleri
# 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.

Basit metin temizleme
df["sehir"] = (
    df["sehir"]
    .astype("string")
    .str.strip()
    .str.lower()
)
Ham değerTemizlenmiş değer
İstanbulistanbul
 ISTANBUL istanbul
istanbulistanbul

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.

Basit IQR yaklaşımı
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)]
Dikkat: Aykırı değer gördüğünüzde otomatik olarak silmek doğru değildir. Gerçek hayattaki büyük bir sipariş veya kampanya etkisi de istatistiksel olarak aykırı görünebilir.

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.

Örnek: hatalı satışları kontrol etmek
# 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.

Satır sayısıBeklenmedik şekilde fazla kayıt silindi mi?
Eksik değerlerTemizleme sonrası kritik boşluklar kaldı mı?
Veri tipleriTarih ve sayısal alanlar doğru tipte mi?
DuplicateTekrar eden kayıtlar temizlendi mi?
KategorilerYazım farkları standart hale geldi mi?
AnalizÖzet istatistikler mantıklı görünüyor mu?

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.

Örnek temizleme fonksiyonu
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 df

Veri Temizlemede En Çok Yapılan Hatalar

HataNeden problem?Daha iyi yaklaşım
Eksik verilerin tamamını silmekGereksiz veri kaybına yol açabilir.Eksikliğin nedenini ve değişkenin önemini incelemek.
Aykırı değerleri otomatik silmekGerçek önemli olaylar kaybolabilir.Önce kaynağını kontrol etmek.
Ham verinin üzerine yazmakGeri dönüş zorlaşır.Ham ve temiz veri setlerini ayırmak.
Kontrol yapmamakTemizleme 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.

Basic data cleaning workflow
  1. Inspect
    the Data
  2. Find
    Problems
  3. Clean
  4. Check
  5. 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.

First checks with pandas
import pandas as pd

df = pd.read_csv("sales.csv")

print(df.shape)
print(df.head())
df.info()
print(df.isna().sum())
shape

Size

Shows quickly how many rows and columns there are.

head()

First records

Checks the real structure of the data through a few sample rows.

info()

Data types

Shows column types and how many values are filled in.

isna()

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.

Checking missing data
# 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())
Important: How you handle missing values depends on the structure of the data set and the goal of the analysis. Deleting a row and filling a value with an estimate do not produce the same analytical result.

3. Finding Duplicate Records

The same record arriving more than once is a common problem, especially when data is merged from different sources.

Checking duplicates
# 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.

Common data type conversions
# 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.

Simple text cleaning
df["city"] = (
    df["city"]
    .astype("string")
    .str.strip()
    .str.lower()
)
Raw valueCleaned value
İstanbulistanbul
 ISTANBUL istanbul
istanbulistanbul

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.

A simple IQR approach
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)]
Careful: Automatically deleting outliers as soon as you see them is not right. A large real-life order or a campaign effect can also look statistically like an outlier.

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.

Example: checking invalid sales
# 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.

Row countWere unexpectedly many records deleted?
Missing valuesAre critical gaps left after cleaning?
Data typesAre date and numeric fields the right type?
DuplicatesWere duplicate records removed?
CategoriesHave spelling differences been standardized?
AnalysisDo the summary statistics look sensible?

10. A Real Cleaning Workflow

In practice, collecting the cleaning steps in a function is tidier than running each piece of code separately.

Example cleaning function
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 df

The Most Common Data Cleaning Mistakes

MistakeWhy is it a problem?Better approach
Deleting all missing dataIt can cause unnecessary data loss.Examine why data is missing and how important the variable is.
Automatically deleting outliersReal, important events can be lost.Check where they come from first.
Overwriting the raw dataIt becomes hard to go back.Keep raw and clean data sets separate.
Not checkingNew 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.”