Python ile Eksik Veri Analizi ve Doldurma
Eksik değerleri doğru belirlemek, oranlarını ölçmek ve uygun yöntemle ele almak analiz sonuçlarını doğrudan etkiler. Bu rehberde pandas ile eksikleri bulmayı, ortalama-medyan-mod ile doldurmayı ve her yöntemin sınırlarını uygulamalı örneklerle göreceksiniz.
- Araçlar

Eksik veri neden önemlidir?
Bir veri kümesinde eksik değer; ölçümün yapılmaması, kullanıcının yanıt vermemesi, sistem aktarım hatası ya da alanın o gözlem için geçerli olmaması gibi farklı nedenlerden kaynaklanabilir. Bu nedenler aynı anlama gelmediğinden, boş hücreleri otomatik olarak sıfırla doldurmak veya tüm eksik satırları silmek çoğu zaman doğru değildir.
Eksik verinin mekanizması için kullanılan kavramsal çerçeveler MCAR (eksiklik gözlenen/ gözlenmeyen bilgilerden bağımsız), MAR (eksiklik gözlenen değişkenlerle ilişkili) ve MNAR (eksiklik, gözlenmeyen değerle ilişkili) biçimindedir. Gerçek veri setinde bu mekanizmaları kesin olarak kanıtlamak genellikle mümkün değildir; alan bilgisi ve duyarlılık analizi gerekir.
Veriyi yükleme ve boş değerleri standartlaştırma
pandas; sayısal dizilerde NaN, tarih alanlarında NaT ve nullable türlerde pd.NA gibi eksik değer temsillerini tanır. Boş metin ("") ve "bilinmiyor" gibi ifadeler varsayılan olarak eksik kabul edilmeyebilir. CSV yüklerken bu değerleri na_values ile tanımlayın.
import pandas as pd
df = pd.read_csv(
"musteri_verisi.csv",
na_values=["", "Bilinmiyor", "N/A"]
)
# Alternatif boşluk ve metin değerlerini ayrıca düzenle
df = df.replace({"yas": {"-": pd.NA}, "sehir": {"yok": pd.NA}})
Dosyanın kaynağına göre na_values listesini uyarlayın. Örneğin “0” bazı alanlarda gerçek ölçüm, bazılarında eksik değer kodu olabilir; alan sahibinden doğrulamadan bunu NA’ya çevirmeyin.
Eksik değerleri tespit etme
isna() her hücre için eksik değer maskesi döndürür. sum() ile sütun başına sayıyı, veri boyutuna bölerek oranı bulabilirsiniz.
# Eksik hücrelerin True/False görünümü
df.isna().head()
# Sütun başına eksik değer adedi ve yüzdesi
missing_count = df.isna().sum()
missing_pct = df.isna().mean().mul(100).round(1)
missing_report = (pd.DataFrame({
"eksik_adet": missing_count,
"eksik_yuzde": missing_pct
})
.sort_values("eksik_yuzde", ascending=False))
print(missing_report)
df.isna().mean() eksik hücreleri True/1 olarak değerlendirip her sütunda ortalama alır; bu nedenle sütun eksik oranını verir. Tüm tablo için genel hücre oranı ve satır bazlı eksikliği ayrıca inceleyin:
overall_missing_pct = df.isna().to_numpy().mean() * 100
row_missing_pct = df.isna().mean(axis=1) * 100
rows_with_any_missing = df.isna().any(axis=1).sum()
print(f"Tablodaki eksik hücre oranı: {overall_missing_pct:.1f}%")
print(f"Eksik içeren satır: {rows_with_any_missing} / {len(df)}")
Eksikliği görselleştirmek için sütun oranlarını yatay çubuk grafikle göstermek yeterli olabilir:
missing_report["eksik_yuzde"].sort_values().plot(
kind="barh", figsize=(8, 5), title="Sütunlara göre eksik veri oranı (%)"
)
plt.xlabel("Eksik hücre yüzdesi")
plt.tight_layout()
Bu grafik için başta import matplotlib.pyplot as plt ekleyin. Sonuçları toplam örnek sayısı ve alan tanımlarıyla birlikte yorumlayın; %30 eksiklik bir veri kaynağında sorun, başka bir ölçüm sürecinde beklenen olabilir.
Uygulamalı örnek veri seti
Şimdi yaş, gelir, deneyim ve şehir alanları bulunan küçük bir tablo oluşturalım. Üretim analizinde bunu CSV’den okuyabilir, fakat örnek veride eksik değerlerin yerini bilerek açıkça belirtiyoruz.
df = pd.DataFrame({
"yas": [22, 35, None, 41, 29, None],
"gelir": [32000, 54000, 47000, None, 39000, 62000],
"deneyim_yil": [1, 8, 5, 12, None, 15],
"sehir": ["Ankara", "İzmir", "Ankara", None, "İstanbul", "İzmir"]
})
print(df.isna().sum())
print((df.isna().mean() * 100).round(1))
Ortalama ile doldurma
Ortalama, sayısal bir alanın eksik değerlerini sütundaki gözlemlerin aritmetik ortalamasıyla doldurur. Dağılım yaklaşık simetrik, aykırı değerler az ve ortalamanın temsil edici olduğu durumlarda pratik bir başlangıç yöntemidir.
df_mean = df.copy()
yas_ort = df_mean["yas"].mean()
df_mean["yas"] = df_mean["yas"].fillna(yas_ort)
print("Yaş için ortalama:", yas_ort)
Eksik değerlerden sonra dağılımın ortalaması yapay biçimde korunurken varyans küçülebilir; gözlemler gerçekte olduğundan birbirine daha yakın görünür. Aykırı gelirler ortalamayı yukarı çekebileceğinden gelir gibi çarpık alanlarda medyanı düşünün.
Medyan ile doldurma
Medyan, değerleri sıraladığınızda ortadaki gözlemdir. Aykırı değerlere ortalamadan daha dayanıklı olduğu için çarpık sayısal dağılımlarda veya uç değerlerin bulunduğu alanlarda sıklıkla tercih edilir.
df_median = df.copy()
for col in ["yas", "gelir", "deneyim_yil"]:
df_median[col] = df_median[col].fillna(df_median[col].median())
print(df_median)
Bu örnek her sütunun medyanını kullanır. Gruplar arasında doğal fark varsa, örneğin gelir şehir ve pozisyona göre belirgin biçimde değişiyorsa grup bazlı medyan daha uygun olabilir; ancak küçük gruplarda medyan hesaplamak kararsızlaşır.
df_grouped = df.copy()
global_median = df_grouped["gelir"].median()
group_median = df_grouped.groupby("sehir")["gelir"].transform("median")
df_grouped["gelir"] = df_grouped["gelir"].fillna(group_median).fillna(global_median)
Grup anahtarının kendisi eksik olan satırlarda ilk doldurma boş kalır; bu yüzden örnekte global medyan yedek olarak kullanılıyor. İmputasyon kuralını iş bağlamına göre seçin ve hangi satırların hangi kuralla doldurulduğunu izleyin.
Mod (en sık görülen değer) ile doldurma
Kategorik değişkenlerde ortalama/medyan anlamlı değildir. Mod, en sık görülen kategoriyi kullanır. Eşit sıklıkta birden fazla mod çıkabilir; pandas mode() bir Series döndürür, bu nedenle ilk değeri seçtiğinizi açıkça belirtebilirsiniz.
df_mode = df.copy()
mode_values = df_mode["sehir"].mode(dropna=True)
if not mode_values.empty:
city_mode = mode_values.iloc[0]
df_mode["sehir"] = df_mode["sehir"].fillna(city_mode)
print("Seçilen mod:", mode_values.iloc[0] if not mode_values.empty else "Mod yok: sütun tamamen boş olabilir")
Mod kullanımı en yaygın sınıfın payını daha da artırır ve kategorilerin dağılımını değiştirebilir. “Bilinmiyor” değerini ayrı bir kategori olarak korumak, bazı iş sorularında modla doldurmaktan daha anlamlıdır.
Hangi yöntemi ne zaman seçmeli?
| Yöntem | Uygun olabileceği durum | Dikkat edilmesi gereken |
|---|---|---|
| Ortalama | Sayısal, yaklaşık simetrik dağılım; belirgin aykırı değer az | Uç değerlerden etkilenir; varyansı daraltabilir. |
| Medyan | Sayısal, çarpık dağılım veya uç değerler | Yine dağılımı ve ilişkileri değiştirebilir. |
| Mod | Kategorik alanlarda sık görülen değeri kullanmak anlamlı | En yaygın kategoriyi baskınlaştırabilir; eşit modlar olabilir. |
| Sabit kategori | Eksikliğin kendisi anlamlı: “Yanıt yok/bilinmiyor” | Yeni bir kategori oluşturmanın model ve rapora etkisini belirtin. |
| Silme | Eksik kayıt az ve silme yanlılık yaratmayacak şekilde gerekçelendirilebiliyorsa | Örneklem boyutu ve temsil gücü azalır. |
| İleri/geri doldurma | Sıralı zaman serisinde kısa boşluklar ve süreklilik varsayımı makulse | Zaman sırasını koruyun; uzun boşluklara körlemesine uygulamayın. |
Tek bir yöntem bütün sütunlara uygulanmak zorunda değildir. Sayısal alanlarda medyan, kategorik alanlarda anlamlı bir “bilinmiyor” kategorisi; tarih/sıralı gözlemlerde ise bağlama uygun zaman serisi yöntemi seçilebilir.
Doldurma öncesi ve sonrası kontrol
İmputasyon sadece boş hücreleri azaltmamalı; analizin anlamını da korumalıdır. Orijinal tabloyu saklayın, dönüşümü kopya üzerinde yapın ve sütun dağılımlarını karşılaştırın.
col = "gelir"
before = df[col].describe()
filled = df[col].fillna(df[col].median())
after = filled.describe()
comparison = pd.concat(
[before.rename("once"), after.rename("sonra")], axis=1
)
print(comparison)
Doldurulan gözlemleri ayrıca işaretlemek de faydalıdır: df["gelir_eksikti"] = df["gelir"].isna(). Böylece raporda değerlerin hangilerinin gözlenmiş, hangilerinin imputasyonla üretilmiş olduğunu ayırt edebilirsiniz.
Makine öğrenmesinde veri sızıntısını önleyin
Model kurarken ortalama, medyan ve mod gibi istatistikleri tüm veri üzerinde hesaplayıp sonra train-test ayırmak, test bilgisinin eğitim sürecine sızmasına yol açabilir. Önce eğitim/test ayrımı yapın; doldurma istatistiklerini yalnızca eğitim bölümünde öğrenip test verisine aynısını uygulayın. pandas ile elle yapılabilir; model hattında scikit-learn SimpleImputer ve Pipeline kullanmak bu adımların çapraz doğrulamada doğru sırada kalmasına yardımcı olur.
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
X_train, X_test = train_test_split(X, test_size=0.2, random_state=42)
imputer = SimpleImputer(strategy="median")
X_train_filled = imputer.fit_transform(X_train)
X_test_filled = imputer.transform(X_test)
Bu örnek sayısal sütunlar içindir. Kategorik sütunlara uygun imputasyon ve kodlama adımları ayrı tasarlanmalıdır.
İyi uygulamalar ve kısa kontrol listesi
- ☐ Boş değer temsilini kaynağa göre doğruladım; sıfır ve boş metni otomatik NA saymadım.
- ☐ Sütun ve satır bazında eksik adet/oranı çıkardım.
- ☐ Eksiklik örüntüsünü ve olası nedenini alan bilgisiyle inceledim.
- ☐ Silme veya doldurma kararını analiz amacı ve yanlılık riskiyle gerekçelendirdim.
- ☐ Ortalama/medyan/mod seçiminde dağılımı ve değişken türünü dikkate aldım.
- ☐ Doldurma öncesi orijinal veriyi korudum, imputasyonları işaretledim.
- ☐ Modelleme varsa istatistikleri yalnızca eğitim verisinde öğrendim.
- ☐ Dönüşüm sonrası dağılımları ve eksik oranlarını tekrar kontrol ettim.
Sonuç
pandas ile eksik veri analizi birkaç satır kodla yapılabilir: isna() ile tespit edin, sum() ve mean() ile adet ve oranları çıkarın, sonra eksikliğin nedenini ve dağılımı inceleyerek yöntemi seçin. Ortalama, medyan ve mod kullanışlı başlangıç seçenekleridir; fakat veri üretim sürecini anlamanın ve sonuçları doğrulamanın yerini tutmazlar.
Kaynaklar
Why does missing data matter?
A missing value in a data set can come from very different places: a measurement that was never taken, a respondent who did not answer, a transfer error in a system, or a field that simply does not apply to that observation. Because those causes do not mean the same thing, filling empty cells with zero automatically or deleting every incomplete row is usually the wrong move.
The conceptual frameworks used for the mechanism behind missing data are MCAR (the missingness is independent of both observed and unobserved information), MAR (the missingness is related to observed variables) and MNAR (the missingness is related to the unobserved value itself). In a real data set it is generally not possible to prove which mechanism applies; you need domain knowledge and a sensitivity analysis.
Loading the data and standardising empty values
pandas recognises representations such as NaN in numeric arrays, NaT in date fields and pd.NA in nullable types. Empty text ("") and expressions like "unknown" may not be treated as missing by default. Declare those values with na_values when you load a CSV.
import pandas as pd
df = pd.read_csv(
"customer_data.csv",
na_values=["", "Unknown", "N/A"]
)
# Handle alternative blanks and text values separately
df = df.replace({"age": {"-": pd.NA}, "city": {"none": pd.NA}})
Adapt the na_values list to the source of the file. A "0", for example, may be a genuine measurement in some fields and a missing-value code in others; do not turn it into NA without confirming with whoever owns the field.
Detecting missing values
isna() returns a missing-value mask for every cell. With sum() you get the count per column, and dividing by the size of the data gives you the proportion.
# A True/False view of the missing cells
df.isna().head()
# Number and percentage of missing values per column
missing_count = df.isna().sum()
missing_pct = df.isna().mean().mul(100).round(1)
missing_report = (pd.DataFrame({
"missing_count": missing_count,
"missing_pct": missing_pct
})
.sort_values("missing_pct", ascending=False))
print(missing_report)
df.isna().mean() treats missing cells as True/1 and averages each column, which is why it gives you the column's missing rate. Examine the overall cell rate for the whole table and the missingness per row as well:
overall_missing_pct = df.isna().to_numpy().mean() * 100
row_missing_pct = df.isna().mean(axis=1) * 100
rows_with_any_missing = df.isna().any(axis=1).sum()
print(f"Share of missing cells in the table: {overall_missing_pct:.1f}%")
print(f"Rows containing a missing value: {rows_with_any_missing} / {len(df)}")
To visualise the missingness, showing the column rates as a horizontal bar chart is often enough:
missing_report["missing_pct"].sort_values().plot(
kind="barh", figsize=(8, 5), title="Missing data rate by column (%)"
)
plt.xlabel("Percentage of missing cells")
plt.tight_layout()
Add import matplotlib.pyplot as plt at the top for this chart. Read the results alongside the total sample size and the field definitions; 30% missing may be a problem in one data source and the expected outcome of a different measurement process.
A worked example data set
Let us build a small table with age, income, experience and city fields. In production analysis you would read this from a CSV, but in the example data we deliberately spell out where the missing values sit.
df = pd.DataFrame({
"age": [22, 35, None, 41, 29, None],
"income": [32000, 54000, 47000, None, 39000, 62000],
"experience_years": [1, 8, 5, 12, None, 15],
"city": ["Ankara", "İzmir", "Ankara", None, "İstanbul", "İzmir"]
})
print(df.isna().sum())
print((df.isna().mean() * 100).round(1))
Filling with the mean
The mean fills a numeric field's missing values with the arithmetic average of the observations in that column. It is a practical starting point when the distribution is roughly symmetric, outliers are few and the mean is representative.
df_mean = df.copy()
age_mean = df_mean["age"].mean()
df_mean["age"] = df_mean["age"].fillna(age_mean)
print("Mean for age:", age_mean)
After the missing values are filled, the mean of the distribution is preserved artificially while the variance can shrink; the observations end up looking closer together than they really are. Since extreme incomes can pull the mean upward, consider the median for skewed fields such as income.
Filling with the median
The median is the middle observation once you sort the values. Because it stands up to outliers better than the mean, it is often preferred for skewed numeric distributions or fields that contain extreme values.
df_median = df.copy()
for col in ["age", "income", "experience_years"]:
df_median[col] = df_median[col].fillna(df_median[col].median())
print(df_median)
This example uses each column's own median. Where there is a natural difference between groups — if income varies noticeably by city and role, say — a group-level median may suit better; but medians computed on small groups become unstable.
df_grouped = df.copy()
global_median = df_grouped["income"].median()
group_median = df_grouped.groupby("city")["income"].transform("median")
df_grouped["income"] = df_grouped["income"].fillna(group_median).fillna(global_median)
On rows where the group key is itself missing, the first fill leaves a blank; that is why the example keeps the global median as a fallback. Choose the imputation rule to fit the business context and keep track of which rows were filled by which rule.
Filling with the mode (the most frequent value)
For categorical variables a mean or median is meaningless. The mode uses the most frequent category. There can be more than one mode at equal frequency; pandas mode() returns a Series, so you can make it explicit that you are taking the first value.
df_mode = df.copy()
mode_values = df_mode["city"].mode(dropna=True)
if not mode_values.empty:
city_mode = mode_values.iloc[0]
df_mode["city"] = df_mode["city"].fillna(city_mode)
print("Mode chosen:", mode_values.iloc[0] if not mode_values.empty else "No mode: the column may be entirely empty")
Using the mode increases the share of the most common class further and can change the distribution of the categories. For some business questions, keeping an "unknown" value as a category of its own is more meaningful than filling with the mode.
Which method should you choose, and when?
| Method | Where it may fit | What to watch for |
|---|---|---|
| Mean | Numeric, roughly symmetric distribution; few pronounced outliers | Affected by extreme values; can narrow the variance. |
| Median | Numeric, skewed distribution or extreme values | Can still change the distribution and the relationships. |
| Mode | Categorical fields where using the frequent value is meaningful | Can make the most common category dominant; there may be tied modes. |
| A fixed category | The missingness itself is meaningful: "no answer / unknown" | State the effect of creating a new category on the model and the report. |
| Deletion | Few incomplete records, and deletion can be justified as not introducing bias | The sample size and how well it represents the population both fall. |
| Forward/backward fill | Short gaps in an ordered time series where continuity is a reasonable assumption | Preserve the time order; do not apply it blindly to long gaps. |
A single method does not have to apply to every column. You might choose the median for numeric fields, a meaningful "unknown" category for categorical ones, and a time-series method suited to the context for dated or ordered observations.
Checking before and after the fill
Imputation should not merely reduce the number of empty cells; it has to preserve the meaning of the analysis too. Keep the original table, do the transformation on a copy, and compare the column distributions.
col = "income"
before = df[col].describe()
filled = df[col].fillna(df[col].median())
after = filled.describe()
comparison = pd.concat(
[before.rename("before"), after.rename("after")], axis=1
)
print(comparison)
Flagging the filled observations separately also helps: df["income_was_missing"] = df["income"].isna(). That way your report can distinguish which values were observed and which were produced by imputation.
Avoid data leakage in machine learning
When you build a model, computing statistics such as the mean, median and mode on the whole data set and only then splitting into train and test can leak test information into the training process. Split first; learn the filling statistics on the training portion alone and apply the same ones to the test data. You can do this by hand with pandas; in a model pipeline, scikit-learn's SimpleImputer and Pipeline help keep these steps in the right order under cross-validation.
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
X_train, X_test = train_test_split(X, test_size=0.2, random_state=42)
imputer = SimpleImputer(strategy="median")
X_train_filled = imputer.fit_transform(X_train)
X_test_filled = imputer.transform(X_test)
This example is for numeric columns. The imputation and encoding steps for categorical columns have to be designed separately.
Good practice and a short checklist
- ☐ I confirmed how empty values are represented in this source, and did not count zero or empty text as NA automatically.
- ☐ I produced the missing count and rate per column and per row.
- ☐ I examined the pattern of missingness and its likely cause with domain knowledge.
- ☐ I justified the decision to delete or fill against the purpose of the analysis and the risk of bias.
- ☐ I took the distribution and the variable type into account when choosing between mean, median and mode.
- ☐ I kept the original data before filling and flagged the imputed values.
- ☐ Where modelling was involved, I learned the statistics on the training data only.
- ☐ I re-checked the distributions and the missing rates after the transformation.
Summary
Missing data analysis in pandas takes only a few lines of code: detect with isna(), get counts and rates with sum() and mean(), then choose a method by examining the reason for the missingness and the distribution. Mean, median and mode are useful starting options, but they do not substitute for understanding how the data was produced or for verifying the results.