Intlrnz commited on
Commit
eb78c90
·
verified ·
1 Parent(s): 85345f4

Upload MissingnessAudit.py

Browse files
Files changed (1) hide show
  1. MissingnessAudit.py +139 -0
MissingnessAudit.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """MissingnessAudit.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/10ktqYR6Cv7gMByA9WSlIqMg-NWywhRU_
8
+ """
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ import matplotlib.pyplot as plt
13
+ import seaborn as sns
14
+ file_path = "DigitalNomadPolicyDataSet.xlsx"
15
+ xls = pd.ExcelFile(file_path)
16
+ print(xls.sheet_names)
17
+
18
+ data = {
19
+ sheet: pd.read_excel(file_path, sheet_name=sheet)
20
+ for sheet in xls.sheet_names
21
+ }
22
+
23
+ # Variable-level missingness
24
+ for sheet_name, df in data.items():
25
+ missing_summary = pd.DataFrame({
26
+ "Variable": df.columns,
27
+ "Missing_Count": df.isna().sum().values,
28
+ "Missing_Percent": np.round(df.isna().mean().values * 100, 2)
29
+ })
30
+ missing_summary = missing_summary.sort_values(
31
+ "Missing_Percent",
32
+ ascending=False
33
+ )
34
+ print("\nTop variables with missing values:")
35
+ print(missing_summary.head(20))
36
+ missing_summary.to_csv(
37
+ f"{sheet_name}_missingness_summary.csv",
38
+ index=False
39
+ )
40
+
41
+ #Dataset-level missingness
42
+ for sheet_name, df in data.items():
43
+ total_cells = np.prod(df.shape)
44
+ missing_cells = df.isna().sum().sum()
45
+ print(f"\n{sheet_name}")
46
+ print(f"Rows: {df.shape[0]:,}")
47
+ print(f"Columns: {df.shape[1]:,}")
48
+ print(f"Total Missing Cells: {missing_cells:,}")
49
+ print(f"Overall Missingness: {100*missing_cells/total_cells:.2f}%")
50
+
51
+ # Country-level missingness
52
+ for sheet_name, df in data.items():
53
+ if 'iso3' in df.columns:
54
+ country_missing = (
55
+ df.groupby('iso3')
56
+ .apply(lambda x: x.isna().mean().mean()*100)
57
+ .reset_index(name='Missing_Percent')
58
+ .sort_values('Missing_Percent', ascending=False)
59
+ )
60
+ country_missing.to_csv(
61
+ f"{sheet_name}_country_missingness.csv",
62
+ index=False
63
+ )
64
+
65
+ print(f"\nTop countries with missing data ({sheet_name})")
66
+ print(country_missing.head(10))
67
+
68
+ # 5. Year-level missingness
69
+
70
+ for sheet_name, df in data.items():
71
+
72
+ if 'year' in df.columns:
73
+
74
+ yearly_missing = (
75
+ df.groupby('year')
76
+ .apply(lambda x: x.isna().mean().mean()*100)
77
+ .reset_index(name='Missing_Percent')
78
+ )
79
+
80
+ yearly_missing.to_csv(
81
+ f"{sheet_name}_year_missingness.csv",
82
+ index=False
83
+ )
84
+
85
+ plt.figure(figsize=(10,5))
86
+ sns.lineplot(
87
+ data=yearly_missing,
88
+ x='year',
89
+ y='Missing_Percent'
90
+ )
91
+ plt.title(f"Missingness by Year: {sheet_name}")
92
+ plt.ylabel("% Missing")
93
+ plt.tight_layout()
94
+ plt.savefig(
95
+ f"{sheet_name}_yearly_missingness.png",
96
+ dpi=300
97
+ )
98
+ plt.close()
99
+
100
+ # --------------------------------------------
101
+ # 6. Missingness Heatmap
102
+
103
+ for sheet_name, df in data.items():
104
+
105
+ plt.figure(figsize=(14,8))
106
+
107
+ sns.heatmap(
108
+ df.isna(),
109
+ cbar=True,
110
+ yticklabels=False
111
+ )
112
+
113
+ plt.title(f"Missing Data Pattern: {sheet_name}")
114
+
115
+ plt.tight_layout()
116
+
117
+ plt.savefig(
118
+ f"{sheet_name}_missingness_heatmap.png",
119
+ dpi=300
120
+ )
121
+
122
+ plt.close()
123
+
124
+ # Data Descriptor Table
125
+
126
+ for sheet_name, df in data.items():
127
+
128
+ audit_table = pd.DataFrame({
129
+ "Variable": df.columns,
130
+ "Data_Type": df.dtypes.astype(str),
131
+ "Missing_Count": df.isna().sum(),
132
+ "Missing_Percent": round(df.isna().mean()*100,2),
133
+ "Unique_Values": df.nunique()
134
+ })
135
+
136
+ audit_table.to_excel(
137
+ f"{sheet_name}_audit_table.xlsx",
138
+ index=False
139
+ )