nnkl1706 commited on
Commit
59244cd
·
verified ·
1 Parent(s): f74da7b

Delete EDA.py

Browse files
Files changed (1) hide show
  1. EDA.py +0 -90
EDA.py DELETED
@@ -1,90 +0,0 @@
1
- import numpy as np
2
- import pandas as pd
3
- import matplotlib.pyplot as plt
4
- import seaborn as sns
5
- from pathlib import Path
6
-
7
- PATH = Path("BuildingsIncomePopulationDataset.csv")
8
- OUT = Path("Visualization")
9
- OUT.mkdir(parents=True, exist_ok=True)
10
- sns.set_theme(style="whitegrid")
11
-
12
- # Load
13
- # Semicolon separated, decimal comma, postal codes keep leading zeros
14
- df = pd.read_csv(PATH, sep=";", decimal=",", encoding="utf-8-sig", dtype={"Postal code": str})
15
- df.columns = ["Postal_code", "Over_18", "Mean_income", "Household_size", "Buildings",
16
- "Households", "Population", "Median_income", "Residential_buildings"]
17
-
18
- print("Dimensions:", df.shape)
19
-
20
- num = df.columns.drop("Postal_code")
21
-
22
- # Verify data
23
- print("Residential buildings > total buildings:", (df.Residential_buildings > df.Buildings).sum())
24
- print("Population / (Households * Household_size), should be ~1:\n",
25
- (df["Population"] / (df.Households * df.Household_size)).describe().round(3), "\n")
26
-
27
- #Deprived data
28
- df["Adult_ratio"] = df.Over_18 / df["Population"].replace(0, np.nan)
29
- df["Income_ratio"] = df.Mean_income / df.Median_income # >1 => right-skewed income
30
- df["Density"] = df["Population"] / df.Buildings # residents per building
31
- df["Residential_ratio"] = df.Residential_buildings / df.Buildings
32
-
33
- print(df[num].describe().T.round(1), "\n")
34
- print("Skewness:\n", df[num].skew().round(2), "\n")
35
-
36
-
37
- core = ["Population", "Households", "Buildings", "Mean_income", "Median_income", "Household_size"]
38
- fig, axes = plt.subplots(2, 3, figsize=(14, 7))
39
- for ax, c in zip(axes.ravel(), core):
40
- sns.histplot(df[c], kde=True, ax=ax, color="Steelblue")
41
- ax.axvline(df[c].median(), color="crimson", ls="--", lw=1, label="Median")
42
- ax.set_title(c); ax.set_xlabel("")
43
- axes[0, 0].legend()
44
- fig.suptitle("Distributions across postal code areas", y=1.0)
45
- fig.tight_layout(); fig.savefig(f"{OUT}/01_distributions.png", dpi=150); plt.close(fig)
46
-
47
- fig, axes = plt.subplots(1, len(core), figsize=(15, 3.5))
48
- for ax, c in zip(axes, core):
49
- sns.boxplot(y=df[c], ax=ax, color="lightsteelblue"); ax.set_title(c); ax.set_ylabel("")
50
- fig.tight_layout(); fig.savefig(f"{OUT}/02_boxplots.png", dpi=150); plt.close(fig)
51
-
52
- # Outliers via 1.5*IQR rule, all columns at once
53
- q1, q3 = df[core].quantile([.25, .75]).values
54
- iqr = q3 - q1
55
- mask = (df[core] < q1 - 1.5 * iqr) | (df[core] > q3 + 1.5 * iqr)
56
- print("IQR outlier counts:\n", mask.sum(), "\n")
57
- print("Postal codes flagged as outliers:\n",
58
- mask.apply(lambda s: df.loc[s, "Postal_code"].tolist()).to_string(), "\n")
59
-
60
- #Bivariate
61
- corr = df[core + ["Over_18", "Residential_buildings"]].corr(method="spearman")
62
- fig, ax = plt.subplots(figsize=(8, 6.5))
63
- sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", center=0, vmin=-1, vmax=1, ax=ax)
64
- ax.set_title("Spearman correlation")
65
- fig.tight_layout(); fig.savefig(f"{OUT}/03_correlation.png", dpi=150); plt.close(fig)
66
- print("Strongest pairs (|rho|, upper triangle):\n",
67
- corr.where(np.triu(np.ones(corr.shape, bool), 1)).stack().abs().nlargest(8).round(2), "\n")
68
-
69
- fig, axes = plt.subplots(1, 3, figsize=(16, 4.8))
70
- sns.scatterplot(data=df, x="Median_income", y="Mean_income", size="Population", sizes=(15, 250),
71
- alpha=.6, ax=axes[0], legend=False)
72
- lim = [df.Median_income.min(), df.Median_income.max()]
73
- axes[0].plot(lim, lim, "k--", lw=1); axes[0].set_title("Mean vs median income (dashed: mean = median)")
74
- sns.regplot(data=df, x="Population", y="Households", ax=axes[1], scatter_kws=dict(alpha=.6))
75
- axes[1].set_title("Inhabitants vs households")
76
- sns.scatterplot(data=df, x="Population", y="Median_income", hue="Household_size", palette="viridis", ax=axes[2])
77
- axes[2].set_title("Inhabitants vs median income")
78
- fig.tight_layout(); fig.savefig(f"{OUT}/04_relationships.png", dpi=150); plt.close(fig)
79
-
80
- #Rankings and structure
81
- cols = ["Postal_code", "Population", "Mean_income", "Median_income", "Income_ratio"]
82
- print("Highest mean income:\n", df.nlargest(5, "Mean_income")[cols].round(2), "\n")
83
- print("Lowest median income:\n", df.nsmallest(5, "Median_income")[cols].round(2), "\n")
84
- print("Largest by population:\n", df.nlargest(5, "Population")[["Postal_code", "Population", "Households", "Buildings"]], "\n")
85
-
86
- # Income inequality: mean/median ratio vs mean income
87
- fig, ax = plt.subplots(figsize=(6.5, 5))
88
- sns.scatterplot(data=df, x="Mean_income", y="Income_ratio", ax=ax)
89
- ax.set_title("Income skew (mean/median) vs mean income")
90
- fig.tight_layout(); fig.savefig(f"{OUT}/05_income_skew.png", dpi=150); plt.close(fig)