EDA.ipynb 85.8 KB
Newer Older
Joaquin Torres's avatar
Joaquin Torres committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### EDA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Libraries"
   ]
  },
  {
   "cell_type": "code",
19
   "execution_count": 1,
Joaquin Torres's avatar
Joaquin Torres committed
20 21 22 23 24 25
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
26
    "import numpy as np\n",
Joaquin Torres's avatar
Joaquin Torres committed
27 28 29 30 31 32
    "from pypair.association import binary_binary, continuous_continuous, binary_continuous\n",
    "\n",
    "from sklearn.feature_selection import VarianceThreshold\n",
    "from sklearn.feature_selection import SelectKBest\n",
    "from sklearn.feature_selection import f_classif\n",
    "from sklearn.feature_selection import mutual_info_classif"
Joaquin Torres's avatar
Joaquin Torres committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Preparing Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Reading and filtering"
   ]
  },
  {
   "cell_type": "code",
51
   "execution_count": 6,
Joaquin Torres's avatar
Joaquin Torres committed
52 53 54
   "metadata": {},
   "outputs": [],
   "source": [
55
    "bd_all = pd.read_spss('17_abril.sav')\n",
Joaquin Torres's avatar
Joaquin Torres committed
56 57 58 59 60 61 62 63 64 65 66 67
    "\n",
    "# Filter the dataset to work only with alcohol patients\n",
    "bd = bd_all[bd_all['Alcohol_DxCIE'] == 'Sí']\n",
    "\n",
    "# Filter the dataset to work only with 'Situacion_tratamiento' == 'Abandono' or 'Alta'\n",
    "bd = bd[(bd['Situacion_tratamiento'] == 'Abandono') | (bd['Situacion_tratamiento'] == 'Alta terapéutica')]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
68
    "##### Defining sets of patients"
Joaquin Torres's avatar
Joaquin Torres committed
69 70 71 72
   ]
  },
  {
   "cell_type": "code",
73
   "execution_count": 7,
Joaquin Torres's avatar
Joaquin Torres committed
74
   "metadata": {},
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\2495984927.py:18: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  conj_post['Group'] = 'Post'\n",
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\2495984927.py:19: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame.\n",
      "Try using .loc[row_indexer,col_indexer] = value instead\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  conj_pre['Group'] = 'Pre'\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
95
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    "# Pre-pandemic\n",
    "conj_pre = bd[bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio y fin prepandemia']\n",
    "# Pre-pandemic abandono\n",
    "pre_abandono = conj_pre[conj_pre['Situacion_tratamiento'] == 'Abandono']\n",
    "# Pre-pandemic alta\n",
    "pre_alta = conj_pre[conj_pre['Situacion_tratamiento'] == 'Alta terapéutica']\n",
    "\n",
    "# Post-pandemic\n",
    "# Merging last two classes to balance sets\n",
    "conj_post = bd[(bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio prepandemia y fin en pandemia') | \n",
    "               (bd['Pandemia_inicio_fin_tratamiento'] == 'inicio y fin en pandemia')]\n",
    "# Post-pandemic abandono\n",
    "post_abandono = conj_post[conj_post['Situacion_tratamiento'] == 'Abandono']\n",
    "# Post-pandemic alta\n",
    "post_alta = conj_post[conj_post['Situacion_tratamiento'] == 'Alta terapéutica']\n",
    "\n",
    "# Concatenate the two data frames and add a new column to distinguish between them. Useful for plots\n",
    "conj_post['Group'] = 'Post'\n",
    "conj_pre['Group'] = 'Pre'\n",
    "combined_pre_post = pd.concat([conj_post, conj_pre])"
   ]
  },
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PRE: 22861\n",
      "\tALTA: 2792\n",
      "\tABANDONO: 20069\n",
      "POST: 10677\n",
      "\tALTA: 1882\n",
      "\tABANDONO: 8795\n"
     ]
    }
   ],
   "source": [
    "# Printing size of different datasets\n",
    "print(f\"PRE: {len(conj_pre)}\")\n",
    "print(f\"\\tALTA: {len(pre_alta)}\")\n",
    "print(f\"\\tABANDONO: {len(pre_abandono)}\")\n",
    "\n",
    "print(f\"POST: {len(conj_post)}\")\n",
    "print(f\"\\tALTA: {len(post_alta)}\")\n",
    "print(f\"\\tABANDONO: {len(post_abandono)}\")"
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
147 148 149 150 151 152 153 154 155 156 157 158
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### First Steps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Inspecting the dataframes"
Joaquin Torres's avatar
Joaquin Torres committed
159 160 161
   ]
  },
  {
162
   "cell_type": "code",
163
   "execution_count": 9,
Joaquin Torres's avatar
Joaquin Torres committed
164
   "metadata": {},
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PRE\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 22861 entries, 0 to 85164\n",
      "Data columns (total 35 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          22861 non-null  float64 \n",
      " 1   Education                            22861 non-null  object  \n",
      " 2   Social_protection                    22861 non-null  object  \n",
      " 3   Job_insecurity                       22861 non-null  object  \n",
      " 4   Housing                              22861 non-null  object  \n",
      " 5   Alterations_early_childhood_develop  22861 non-null  object  \n",
      " 6   Social_inclusion                     22861 non-null  object  \n",
      " 7   Risk_stigma                          21606 non-null  category\n",
      " 8   Structural_conflic                   22861 non-null  float64 \n",
      " 9   Age                                  22852 non-null  float64 \n",
      " 10  Sex                                  22861 non-null  object  \n",
      " 11  NumHijos                             21647 non-null  float64 \n",
      " 12  Smoking                              22861 non-null  object  \n",
      " 13  Biological_vulnerability             22861 non-null  object  \n",
      " 14  Alcohol_DxCIE                        22861 non-null  object  \n",
      " 15  Opiaceos_DxCIE                       22861 non-null  object  \n",
      " 16  Cannabis_DXCIE                       22861 non-null  object  \n",
      " 17  BZD_DxCIE                            22861 non-null  object  \n",
      " 18  Cocaina_DxCIE                        22861 non-null  object  \n",
      " 19  Alucinogenos_DXCIE                   22861 non-null  object  \n",
      " 20  Tabaco_DXCIE                         22861 non-null  object  \n",
      " 21  FrecuenciaConsumo30Dias              22861 non-null  object  \n",
      " 22  Años_consumo_droga                   22342 non-null  float64 \n",
      " 23  OtrosDx_Psiquiatrico                 22861 non-null  object  \n",
      " 24  Tx_previos                           22861 non-null  object  \n",
      " 25  Adherencia_tto_recalc                22861 non-null  float64 \n",
      " 26  Tiempo_tx                            22861 non-null  float64 \n",
      " 27  Readmisiones_estudios                22861 non-null  object  \n",
      " 28  Situacion_tratamiento                22861 non-null  object  \n",
      " 29  Periodos_COVID                       22861 non-null  object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      22861 non-null  object  \n",
      " 31  Nreadmision                          22861 non-null  float64 \n",
      " 32  Readmisiones_PRECOVID                22861 non-null  float64 \n",
      " 33  Readmisiones_COVID                   22861 non-null  float64 \n",
      " 34  Group                                22861 non-null  object  \n",
      "dtypes: category(1), float64(10), object(24)\n",
      "memory usage: 6.1+ MB\n",
      "None\n",
      "-------------------------------\n",
      "PRE-ABANDONO\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 20069 entries, 0 to 85164\n",
      "Data columns (total 34 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          20069 non-null  float64 \n",
      " 1   Education                            20069 non-null  object  \n",
      " 2   Social_protection                    20069 non-null  object  \n",
      " 3   Job_insecurity                       20069 non-null  object  \n",
      " 4   Housing                              20069 non-null  object  \n",
      " 5   Alterations_early_childhood_develop  20069 non-null  object  \n",
      " 6   Social_inclusion                     20069 non-null  object  \n",
      " 7   Risk_stigma                          18919 non-null  category\n",
      " 8   Structural_conflic                   20069 non-null  float64 \n",
      " 9   Age                                  20061 non-null  float64 \n",
      " 10  Sex                                  20069 non-null  object  \n",
      " 11  NumHijos                             18958 non-null  float64 \n",
      " 12  Smoking                              20069 non-null  object  \n",
      " 13  Biological_vulnerability             20069 non-null  object  \n",
      " 14  Alcohol_DxCIE                        20069 non-null  object  \n",
      " 15  Opiaceos_DxCIE                       20069 non-null  object  \n",
      " 16  Cannabis_DXCIE                       20069 non-null  object  \n",
      " 17  BZD_DxCIE                            20069 non-null  object  \n",
      " 18  Cocaina_DxCIE                        20069 non-null  object  \n",
      " 19  Alucinogenos_DXCIE                   20069 non-null  object  \n",
      " 20  Tabaco_DXCIE                         20069 non-null  object  \n",
      " 21  FrecuenciaConsumo30Dias              20069 non-null  object  \n",
      " 22  Años_consumo_droga                   19609 non-null  float64 \n",
      " 23  OtrosDx_Psiquiatrico                 20069 non-null  object  \n",
      " 24  Tx_previos                           20069 non-null  object  \n",
      " 25  Adherencia_tto_recalc                20069 non-null  float64 \n",
      " 26  Tiempo_tx                            20069 non-null  float64 \n",
      " 27  Readmisiones_estudios                20069 non-null  object  \n",
      " 28  Situacion_tratamiento                20069 non-null  object  \n",
      " 29  Periodos_COVID                       20069 non-null  object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      20069 non-null  object  \n",
      " 31  Nreadmision                          20069 non-null  float64 \n",
      " 32  Readmisiones_PRECOVID                20069 non-null  float64 \n",
      " 33  Readmisiones_COVID                   20069 non-null  float64 \n",
      "dtypes: category(1), float64(10), object(23)\n",
      "memory usage: 5.2+ MB\n",
      "None\n",
      "-------------------------------\n",
      "PRE-ALTA\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 2792 entries, 23 to 85159\n",
      "Data columns (total 34 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          2792 non-null   float64 \n",
      " 1   Education                            2792 non-null   object  \n",
      " 2   Social_protection                    2792 non-null   object  \n",
      " 3   Job_insecurity                       2792 non-null   object  \n",
      " 4   Housing                              2792 non-null   object  \n",
      " 5   Alterations_early_childhood_develop  2792 non-null   object  \n",
      " 6   Social_inclusion                     2792 non-null   object  \n",
      " 7   Risk_stigma                          2687 non-null   category\n",
      " 8   Structural_conflic                   2792 non-null   float64 \n",
      " 9   Age                                  2791 non-null   float64 \n",
      " 10  Sex                                  2792 non-null   object  \n",
      " 11  NumHijos                             2689 non-null   float64 \n",
      " 12  Smoking                              2792 non-null   object  \n",
      " 13  Biological_vulnerability             2792 non-null   object  \n",
      " 14  Alcohol_DxCIE                        2792 non-null   object  \n",
      " 15  Opiaceos_DxCIE                       2792 non-null   object  \n",
      " 16  Cannabis_DXCIE                       2792 non-null   object  \n",
      " 17  BZD_DxCIE                            2792 non-null   object  \n",
      " 18  Cocaina_DxCIE                        2792 non-null   object  \n",
      " 19  Alucinogenos_DXCIE                   2792 non-null   object  \n",
      " 20  Tabaco_DXCIE                         2792 non-null   object  \n",
      " 21  FrecuenciaConsumo30Dias              2792 non-null   object  \n",
      " 22  Años_consumo_droga                   2733 non-null   float64 \n",
      " 23  OtrosDx_Psiquiatrico                 2792 non-null   object  \n",
      " 24  Tx_previos                           2792 non-null   object  \n",
      " 25  Adherencia_tto_recalc                2792 non-null   float64 \n",
      " 26  Tiempo_tx                            2792 non-null   float64 \n",
      " 27  Readmisiones_estudios                2792 non-null   object  \n",
      " 28  Situacion_tratamiento                2792 non-null   object  \n",
      " 29  Periodos_COVID                       2792 non-null   object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      2792 non-null   object  \n",
      " 31  Nreadmision                          2792 non-null   float64 \n",
      " 32  Readmisiones_PRECOVID                2792 non-null   float64 \n",
      " 33  Readmisiones_COVID                   2792 non-null   float64 \n",
      "dtypes: category(1), float64(10), object(23)\n",
      "memory usage: 744.5+ KB\n",
      "None\n",
      "-------------------------------\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "POST\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 10677 entries, 11 to 85156\n",
      "Data columns (total 35 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          10677 non-null  float64 \n",
      " 1   Education                            10677 non-null  object  \n",
      " 2   Social_protection                    10677 non-null  object  \n",
      " 3   Job_insecurity                       10677 non-null  object  \n",
      " 4   Housing                              10677 non-null  object  \n",
      " 5   Alterations_early_childhood_develop  10677 non-null  object  \n",
      " 6   Social_inclusion                     10677 non-null  object  \n",
      " 7   Risk_stigma                          10085 non-null  category\n",
      " 8   Structural_conflic                   10677 non-null  float64 \n",
      " 9   Age                                  10676 non-null  float64 \n",
      " 10  Sex                                  10677 non-null  object  \n",
      " 11  NumHijos                             10103 non-null  float64 \n",
      " 12  Smoking                              10677 non-null  object  \n",
      " 13  Biological_vulnerability             10677 non-null  object  \n",
      " 14  Alcohol_DxCIE                        10677 non-null  object  \n",
      " 15  Opiaceos_DxCIE                       10677 non-null  object  \n",
      " 16  Cannabis_DXCIE                       10677 non-null  object  \n",
      " 17  BZD_DxCIE                            10677 non-null  object  \n",
      " 18  Cocaina_DxCIE                        10677 non-null  object  \n",
      " 19  Alucinogenos_DXCIE                   10677 non-null  object  \n",
      " 20  Tabaco_DXCIE                         10677 non-null  object  \n",
      " 21  FrecuenciaConsumo30Dias              10677 non-null  object  \n",
      " 22  Años_consumo_droga                   10478 non-null  float64 \n",
      " 23  OtrosDx_Psiquiatrico                 10677 non-null  object  \n",
      " 24  Tx_previos                           10677 non-null  object  \n",
      " 25  Adherencia_tto_recalc                10677 non-null  float64 \n",
      " 26  Tiempo_tx                            10677 non-null  float64 \n",
      " 27  Readmisiones_estudios                10677 non-null  object  \n",
      " 28  Situacion_tratamiento                10677 non-null  object  \n",
      " 29  Periodos_COVID                       10677 non-null  object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      10677 non-null  object  \n",
      " 31  Nreadmision                          10677 non-null  float64 \n",
      " 32  Readmisiones_PRECOVID                10677 non-null  float64 \n",
      " 33  Readmisiones_COVID                   10677 non-null  float64 \n",
      " 34  Group                                10677 non-null  object  \n",
      "dtypes: category(1), float64(10), object(24)\n",
      "memory usage: 2.9+ MB\n",
      "None\n",
      "-------------------------------\n",
      "POST-ABANDONO\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 8795 entries, 11 to 85156\n",
      "Data columns (total 34 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          8795 non-null   float64 \n",
      " 1   Education                            8795 non-null   object  \n",
      " 2   Social_protection                    8795 non-null   object  \n",
      " 3   Job_insecurity                       8795 non-null   object  \n",
      " 4   Housing                              8795 non-null   object  \n",
      " 5   Alterations_early_childhood_develop  8795 non-null   object  \n",
      " 6   Social_inclusion                     8795 non-null   object  \n",
      " 7   Risk_stigma                          8308 non-null   category\n",
      " 8   Structural_conflic                   8795 non-null   float64 \n",
      " 9   Age                                  8794 non-null   float64 \n",
      " 10  Sex                                  8795 non-null   object  \n",
      " 11  NumHijos                             8325 non-null   float64 \n",
      " 12  Smoking                              8795 non-null   object  \n",
      " 13  Biological_vulnerability             8795 non-null   object  \n",
      " 14  Alcohol_DxCIE                        8795 non-null   object  \n",
      " 15  Opiaceos_DxCIE                       8795 non-null   object  \n",
      " 16  Cannabis_DXCIE                       8795 non-null   object  \n",
      " 17  BZD_DxCIE                            8795 non-null   object  \n",
      " 18  Cocaina_DxCIE                        8795 non-null   object  \n",
      " 19  Alucinogenos_DXCIE                   8795 non-null   object  \n",
      " 20  Tabaco_DXCIE                         8795 non-null   object  \n",
      " 21  FrecuenciaConsumo30Dias              8795 non-null   object  \n",
      " 22  Años_consumo_droga                   8627 non-null   float64 \n",
      " 23  OtrosDx_Psiquiatrico                 8795 non-null   object  \n",
      " 24  Tx_previos                           8795 non-null   object  \n",
      " 25  Adherencia_tto_recalc                8795 non-null   float64 \n",
      " 26  Tiempo_tx                            8795 non-null   float64 \n",
      " 27  Readmisiones_estudios                8795 non-null   object  \n",
      " 28  Situacion_tratamiento                8795 non-null   object  \n",
      " 29  Periodos_COVID                       8795 non-null   object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      8795 non-null   object  \n",
      " 31  Nreadmision                          8795 non-null   float64 \n",
      " 32  Readmisiones_PRECOVID                8795 non-null   float64 \n",
      " 33  Readmisiones_COVID                   8795 non-null   float64 \n",
      "dtypes: category(1), float64(10), object(23)\n",
      "memory usage: 2.3+ MB\n",
      "None\n",
      "-------------------------------\n",
      "POST-ALTA\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 1882 entries, 258 to 85149\n",
      "Data columns (total 34 columns):\n",
      " #   Column                               Non-Null Count  Dtype   \n",
      "---  ------                               --------------  -----   \n",
      " 0   CODPROYECTO                          1882 non-null   float64 \n",
      " 1   Education                            1882 non-null   object  \n",
      " 2   Social_protection                    1882 non-null   object  \n",
      " 3   Job_insecurity                       1882 non-null   object  \n",
      " 4   Housing                              1882 non-null   object  \n",
      " 5   Alterations_early_childhood_develop  1882 non-null   object  \n",
      " 6   Social_inclusion                     1882 non-null   object  \n",
      " 7   Risk_stigma                          1777 non-null   category\n",
      " 8   Structural_conflic                   1882 non-null   float64 \n",
      " 9   Age                                  1882 non-null   float64 \n",
      " 10  Sex                                  1882 non-null   object  \n",
      " 11  NumHijos                             1778 non-null   float64 \n",
      " 12  Smoking                              1882 non-null   object  \n",
      " 13  Biological_vulnerability             1882 non-null   object  \n",
      " 14  Alcohol_DxCIE                        1882 non-null   object  \n",
      " 15  Opiaceos_DxCIE                       1882 non-null   object  \n",
      " 16  Cannabis_DXCIE                       1882 non-null   object  \n",
      " 17  BZD_DxCIE                            1882 non-null   object  \n",
      " 18  Cocaina_DxCIE                        1882 non-null   object  \n",
      " 19  Alucinogenos_DXCIE                   1882 non-null   object  \n",
      " 20  Tabaco_DXCIE                         1882 non-null   object  \n",
      " 21  FrecuenciaConsumo30Dias              1882 non-null   object  \n",
      " 22  Años_consumo_droga                   1851 non-null   float64 \n",
      " 23  OtrosDx_Psiquiatrico                 1882 non-null   object  \n",
      " 24  Tx_previos                           1882 non-null   object  \n",
      " 25  Adherencia_tto_recalc                1882 non-null   float64 \n",
      " 26  Tiempo_tx                            1882 non-null   float64 \n",
      " 27  Readmisiones_estudios                1882 non-null   object  \n",
      " 28  Situacion_tratamiento                1882 non-null   object  \n",
      " 29  Periodos_COVID                       1882 non-null   object  \n",
      " 30  Pandemia_inicio_fin_tratamiento      1882 non-null   object  \n",
      " 31  Nreadmision                          1882 non-null   float64 \n",
      " 32  Readmisiones_PRECOVID                1882 non-null   float64 \n",
      " 33  Readmisiones_COVID                   1882 non-null   float64 \n",
      "dtypes: category(1), float64(10), object(23)\n",
      "memory usage: 501.9+ KB\n",
      "None\n",
      "-------------------------------\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
   "source": [
    "print(\"PRE\")\n",
    "print(conj_pre.info())\n",
    "print (\"-------------------------------\")\n",
    "print(\"PRE-ABANDONO\")\n",
    "print(pre_abandono.info())\n",
    "print (\"-------------------------------\")\n",
    "print(\"PRE-ALTA\")\n",
    "print(pre_alta.info())\n",
    "print (\"-------------------------------\")\n",
    "\n",
    "print(\"\\n\\n\\n\")\n",
    "\n",
    "print (\"POST\")\n",
    "print(conj_post.info())\n",
    "print (\"-------------------------------\")\n",
    "print(\"POST-ABANDONO\")\n",
    "print(post_abandono.info())\n",
    "print (\"-------------------------------\")\n",
    "print(\"POST-ALTA\")\n",
    "print(post_alta.info())\n",
    "print (\"-------------------------------\")"
   ]
  },
  {
   "cell_type": "markdown",
Joaquin Torres's avatar
Joaquin Torres committed
469 470
   "metadata": {},
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
471
    "##### Replacing unknown values with the mode"
472 473 474 475
   ]
  },
  {
   "cell_type": "code",
476
   "execution_count": 10,
477
   "metadata": {},
478 479 480 481 482 483 484 485 486 487
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Live with families or friends' 'live alone' 'live in institutions' '9.0']\n",
      "['Live with families or friends' 'live alone' 'live in institutions']\n"
     ]
    }
   ],
488
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
489 490 491 492 493 494
    "# 9.0 represents unknown according to Variables.docx \n",
    "print(bd['Social_inclusion'].unique())\n",
    "mode_soc_inc = bd['Social_inclusion'].mode()[0]\n",
    "# print(mode_soc_inc)\n",
    "bd['Social_inclusion'] = bd['Social_inclusion'].replace('9.0', mode_soc_inc)\n",
    "print(bd['Social_inclusion'].unique())"
495 496 497 498
   ]
  },
  {
   "cell_type": "code",
499
   "execution_count": 11,
500
   "metadata": {},
501 502 503 504 505 506 507 508 509 510 511 512
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['No alterations (first exposure at 11 or more years)'\n",
      " 'Alterations (first exposure before 11 years old)' '9']\n",
      "['No alterations (first exposure at 11 or more years)'\n",
      " 'Alterations (first exposure before 11 years old)']\n"
     ]
    }
   ],
513
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
514 515 516 517
    "print(bd['Alterations_early_childhood_develop'].unique())\n",
    "mode_alt = bd['Alterations_early_childhood_develop'].mode()[0]\n",
    "bd['Alterations_early_childhood_develop'] = bd['Alterations_early_childhood_develop'].replace('9', mode_alt)\n",
    "print(bd['Alterations_early_childhood_develop'].unique())"
Joaquin Torres's avatar
Joaquin Torres committed
518 519 520 521
   ]
  },
  {
   "cell_type": "code",
522
   "execution_count": 12,
Joaquin Torres's avatar
Joaquin Torres committed
523
   "metadata": {},
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[NaN, 'Yes', 'No']\n",
      "Categories (3, object): [99.0, 'No', 'Yes']\n",
      "[NaN, 'Yes', 'No']\n",
      "Categories (2, object): ['No', 'Yes']\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\1073322024.py:3: FutureWarning: The behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead.\n",
      "  bd['Risk_stigma'] = bd['Risk_stigma'].replace(99.0, mode_stigma)\n"
     ]
    }
   ],
544 545
   "source": [
    "print(bd['Risk_stigma'].unique())\n",
Joaquin Torres's avatar
Joaquin Torres committed
546 547
    "mode_stigma = bd['Risk_stigma'].mode()[0]\n",
    "bd['Risk_stigma'] = bd['Risk_stigma'].replace(99.0, mode_stigma)\n",
548 549 550 551 552
    "print(bd['Risk_stigma'].unique())"
   ]
  },
  {
   "cell_type": "code",
553
   "execution_count": 13,
554
   "metadata": {},
555 556 557 558 559 560 561 562 563 564
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[nan  0.  1.  2.  3.  4.  5.  8. 10.  6. 11. 12.  9.  7. 99. 14. 15.]\n",
      "[nan  0.  1.  2.  3.  4.  5.  8. 10.  6. 11. 12.  9.  7. 14. 15.]\n"
     ]
    }
   ],
565 566
   "source": [
    "print(bd['NumHijos'].unique())\n",
Joaquin Torres's avatar
Joaquin Torres committed
567 568
    "mode_hijos = bd['NumHijos'].mode()[0]\n",
    "bd['NumHijos'] = bd['NumHijos'].replace(99.0, mode_hijos)\n",
569 570 571
    "print(bd['NumHijos'].unique())"
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
572 573 574 575 576 577 578 579 580
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Quantifying Null Values"
   ]
  },
  {
   "cell_type": "code",
581
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
582
   "metadata": {},
583
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
584 585 586
   "source": [
    "print(f\"Total missing values Age: {bd['Age'].isnull().sum()}\")\n",
    "print(f\"Total missing values Años_consumo_droga: {bd['Años_consumo_droga'].isnull().sum()}\")\n",
587 588
    "print(f\"Total missing values Risk_stigma: {bd['Risk_stigma'].isnull().sum()}\")\n",
    "print(f\"Total missing values NumHijos: {bd['NumHijos'].isnull().sum()}\")\n",
Joaquin Torres's avatar
Joaquin Torres committed
589 590 591 592
    "\n",
    "print(\"\\tCONJUNTO PREPANDEMIA\")\n",
    "print(f\"\\t\\tMissing values Age: {conj_pre['Age'].isnull().sum()}\")\n",
    "print(f\"\\t\\tMissing values Años_consumo_droga: {conj_pre['Años_consumo_droga'].isnull().sum()}\")\n",
593 594
    "print(f\"\\t\\tMissing values Risk_stigma: {conj_pre['Risk_stigma'].isnull().sum()}\")\n",
    "print(f\"\\t\\tMissing values NumHijos: {conj_pre['NumHijos'].isnull().sum()}\")\n",
Joaquin Torres's avatar
Joaquin Torres committed
595 596 597
    "\n",
    "print(\"\\tCONJUNTO POSTPANDEMIA\")\n",
    "print(f\"\\t\\tMissing values Age: {conj_post['Age'].isnull().sum()}\")\n",
598 599 600
    "print(f\"\\t\\tMissing values Años_consumo_droga: {conj_post['Años_consumo_droga'].isnull().sum()}\")\n",
    "print(f\"\\t\\tMissing values Risk_stigma: {conj_post['Risk_stigma'].isnull().sum()}\")\n",
    "print(f\"\\t\\tMissing values NumHijos: {conj_post['NumHijos'].isnull().sum()}\")"
Joaquin Torres's avatar
Joaquin Torres committed
601 602
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
603 604 605 606 607 608 609 610 611
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Replacing missing values with mode"
   ]
  },
  {
   "cell_type": "code",
612
   "execution_count": 14,
Joaquin Torres's avatar
Joaquin Torres committed
613
   "metadata": {},
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\3303146707.py:2: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
      "The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
      "\n",
      "For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
      "\n",
      "\n",
      "  bd['Age'].fillna(age_mode, inplace=True)\n",
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\3303146707.py:5: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
      "The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
      "\n",
      "For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
      "\n",
      "\n",
      "  bd['Años_consumo_droga'].fillna(años_consumo_mode, inplace=True)\n",
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\3303146707.py:8: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
      "The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
      "\n",
      "For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
      "\n",
      "\n",
      "  bd['Risk_stigma'].fillna(risk_stigma_mode, inplace=True)\n",
      "C:\\Users\\Joaquín Torres\\AppData\\Local\\Temp\\ipykernel_19000\\3303146707.py:11: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.\n",
      "The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.\n",
      "\n",
      "For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.\n",
      "\n",
      "\n",
      "  bd['NumHijos'].fillna(num_hijos_mode, inplace=True)\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
650 651 652 653 654 655 656 657 658 659 660 661 662 663
   "source": [
    "age_mode = bd['Age'].mode()[0]\n",
    "bd['Age'].fillna(age_mode, inplace=True)\n",
    "\n",
    "años_consumo_mode = bd['Años_consumo_droga'].mode()[0]\n",
    "bd['Años_consumo_droga'].fillna(años_consumo_mode, inplace=True)\n",
    "\n",
    "risk_stigma_mode = bd['Risk_stigma'].mode()[0]\n",
    "bd['Risk_stigma'].fillna(risk_stigma_mode, inplace=True)\n",
    "\n",
    "num_hijos_mode = bd['NumHijos'].mode()[0]\n",
    "bd['NumHijos'].fillna(num_hijos_mode, inplace=True)"
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Distribution of variables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Classifying variables into numerical and discrete/categorical "
   ]
  },
  {
   "cell_type": "code",
680
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
681 682 683 684 685
   "metadata": {},
   "outputs": [],
   "source": [
    "disc_atts = ['Education', 'Social_protection', 'Job_insecurity', 'Housing',\n",
    "        'Alterations_early_childhood_develop', 'Social_inclusion',\n",
686 687 688 689
    "        'Risk_stigma', 'Sex', 'NumHijos', 'Smoking', 'Biological_vulnerability',\n",
    "        'Opiaceos_DxCIE', 'Cannabis_DXCIE', 'BZD_DxCIE', 'Cocaina_DxCIE',\n",
    "        'Alucinogenos_DXCIE', 'Tabaco_DXCIE', 'FrecuenciaConsumo30Dias',\n",
    "        'OtrosDx_Psiquiatrico', 'Tx_previos', 'Readmisiones_estudios', 'Nreadmision'\n",
Joaquin Torres's avatar
Joaquin Torres committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    "        ]\n",
    "\n",
    "num_atts = ['Structural_conflic', 'Adherencia_tto_recalc', 'Age', 'Años_consumo_droga', 'Tiempo_tx']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Distribution of discrete attributes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Count plots"
   ]
  },
  {
   "cell_type": "code",
711
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
712
   "metadata": {},
713
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
   "source": [
    "fig, axs = plt.subplots(len(disc_atts), 1, figsize=(15, 5*len(disc_atts)))\n",
    "plt.subplots_adjust(hspace=0.75, wspace=1.25)\n",
    "\n",
    "for i, disc_att in enumerate(disc_atts):\n",
    "    ax = sns.countplot(x=disc_att, data=combined_pre_post, hue=combined_pre_post[['Situacion_tratamiento', 'Group']].apply(tuple, axis=1),\n",
    "                       hue_order=[('Abandono', 'Pre'),('Alta terapéutica', 'Pre'), ('Abandono', 'Post'), ('Alta terapéutica', 'Post')],\n",
    "                       ax=axs[i])\n",
    "    ax.set_title(disc_att, fontsize=16, fontweight='bold')\n",
    "    ax.get_legend().set_title(\"Groups\")\n",
    "    \n",
    "    # Adding count annotations\n",
    "    for p in ax.patches:\n",
    "        if p.get_label() == '_nolegend_':\n",
    "            ax.annotate(format(p.get_height(), '.0f'), \n",
    "                        (p.get_x() + p.get_width() / 2., p.get_height()), \n",
    "                        ha = 'center', va = 'center', \n",
    "                        xytext = (0, 9), \n",
    "                        textcoords = 'offset points')\n",
    "\n",
    "# Adjust layout to prevent overlapping titles\n",
    "plt.tight_layout()\n",
    "\n",
737 738
    "# Save the figure in SVG format with DPI=600 in the \"./EDA_plots\" folder\n",
    "plt.savefig('./EDA_plots/countplots.svg', dpi=600, bbox_inches='tight')"
Joaquin Torres's avatar
Joaquin Torres committed
739 740 741 742 743 744 745 746 747 748 749
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Normalized count plots"
   ]
  },
  {
   "cell_type": "code",
750
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
   "metadata": {},
   "outputs": [],
   "source": [
    "# Function to plot countplot \n",
    "def plot_count_perc_norm(i: int, group:int, disc_att:str) -> None:\n",
    "    \"\"\"\n",
    "        group: 1 (all), 2 (pre), 3 (post) \n",
    "    \"\"\"\n",
    "\n",
    "    # Define data to work with based on group\n",
    "    if group == 1:\n",
    "        df = bd \n",
    "    elif group == 2:\n",
    "        df = conj_pre\n",
    "    elif group == 3:\n",
    "        df = conj_post\n",
    "\n",
    "    # GOAL: find percentage of each possible category within the total of its situacion_tto subset\n",
    "    # Group data by 'Situacion_tratamiento' and 'Education' and count occurrences\n",
    "    grouped_counts = df.groupby(['Situacion_tratamiento', disc_att]).size().reset_index(name='count')\n",
    "    # Calculate total count for each 'Situacion_tratamiento' group\n",
    "    total_counts = df.groupby('Situacion_tratamiento')[disc_att].count()\n",
    "    # Divide each count by its corresponding total count and calculate percentage\n",
    "    grouped_counts['percentage'] = grouped_counts.apply(lambda row: row['count'] / total_counts[row['Situacion_tratamiento']] * 100, axis=1)\n",
    "    \n",
    "    # Follow the same order in plot as in computations\n",
    "    col_order = grouped_counts[grouped_counts['Situacion_tratamiento'] == 'Abandono'][disc_att].tolist()\n",
    "\n",
    "    # Create countplot and split each bar into two based on the value of sit_tto\n",
    "    ax = sns.countplot(x=disc_att, hue='Situacion_tratamiento', data=df, order=col_order, ax=axs[i, group-2])\n",
    "\n",
    "    # Adjust y-axis to represent percentages out of the total count\n",
    "    ax.set_ylim(0, 100)\n",
    "\n",
    "    percentages = grouped_counts['percentage']\n",
    "    for i, p in enumerate(ax.patches):\n",
    "        # Skip going over the legend values\n",
    "        if p.get_label() == \"_nolegend_\":\n",
    "            # Set height to corresponding percentage and annotate result\n",
    "            height = percentages[i]\n",
    "            p.set_height(height)\n",
    "            ax.annotate(f'{height:.2f}%', (p.get_x() + p.get_width() / 2., height),\n",
    "                        ha='center', va='bottom', fontsize=6, color='black', xytext=(0, 5),\n",
    "                        textcoords='offset points')"
   ]
  },
  {
   "cell_type": "code",
799
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
800
   "metadata": {},
801
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
   "source": [
    "fig, axs = plt.subplots(len(disc_atts), 2, figsize=(15, 7*len(disc_atts)))\n",
    "plt.subplots_adjust(hspace=0.75, wspace=1.5)\n",
    "\n",
    "for i, disc_att in enumerate(disc_atts):\n",
    "\n",
    "    # # 1: ALL    \n",
    "    # plot_count_perc_norm(i, 1, disc_att)\n",
    "    # axs[i, 0].set_title(\"\\nALL\")\n",
    "    # axs[i, 0].set_xlabel(disc_att, fontweight='bold')\n",
    "    # axs[i, 0].set_ylabel(\"% of total within its Sit_tto group\")\n",
    "    # axs[i, 0].tick_params(axis='x', rotation=90)\n",
    "    \n",
    "    # 2: PRE\n",
    "    plot_count_perc_norm(i, 2, disc_att)\n",
    "    axs[i, 0].set_title(\"\\nPRE\")\n",
    "    axs[i, 0].set_xlabel(disc_att, fontweight='bold')\n",
    "    axs[i, 0].set_ylabel(\"% of total within its Sit_tto group\")\n",
    "    axs[i, 0].tick_params(axis='x', rotation=90)\n",
    "\n",
    "    # 3: POST\n",
    "    plot_count_perc_norm(i, 3, disc_att)\n",
    "    axs[i, 1].set_title(\"\\nPOST\")\n",
    "    axs[i, 1].set_xlabel(disc_att, fontweight='bold')\n",
    "    axs[i, 1].set_ylabel(\"% of total within its Sit_tto group\")\n",
    "    axs[i, 1].tick_params(axis='x', rotation=90)\n",
    "\n",
    "    \n",
    "# Adjust layout to prevent overlapping titles\n",
    "plt.tight_layout()\n",
    "\n",
833 834
    "# Save the figure in SVG format with DPI=600 in the \"./EDA_plots\" folder\n",
    "plt.savefig('./EDA_plots/norm_countplots.svg', dpi=600, bbox_inches='tight')"
Joaquin Torres's avatar
Joaquin Torres committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Distribution of numeric attributes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Summary statistics"
   ]
  },
  {
   "cell_type": "code",
853
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
854
   "metadata": {},
855
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
856 857 858 859 860 861 862 863 864 865 866 867 868
   "source": [
    "print(bd[num_atts].describe())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Boxplots"
   ]
  },
  {
   "cell_type": "code",
869
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
870
   "metadata": {},
871
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
   "source": [
    "fig, axs = plt.subplots(len(num_atts), 1, figsize=(12, 5*len(num_atts)))\n",
    "plt.subplots_adjust(hspace=0.75, wspace=1.5)\n",
    "\n",
    "for i, num_att in enumerate(num_atts):\n",
    "    plt.subplot(len(num_atts), 1, i+1)\n",
    "    sns.boxplot(\n",
    "        data=combined_pre_post,\n",
    "        x = num_att,\n",
    "        y = 'Group',\n",
    "        hue='Situacion_tratamiento',\n",
    "    )\n",
    "\n",
    "# Adjust layout to prevent overlapping titles\n",
    "plt.tight_layout()\n",
    "\n",
888 889
    "# Save the figure in SVG format with DPI=600 in the \"./EDA_plots\" folder\n",
    "plt.savefig('./EDA_plots/boxplots.svg', dpi=600, bbox_inches='tight')"
Joaquin Torres's avatar
Joaquin Torres committed
890 891 892 893 894 895 896 897 898 899 900
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Histograms"
   ]
  },
  {
   "cell_type": "code",
901
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
902
   "metadata": {},
903
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
   "source": [
    "fig, axs = plt.subplots(len(num_atts), 3, figsize=(15, 6*len(num_atts)))\n",
    "plt.subplots_adjust(hspace=0.75, wspace=1.5)\n",
    "\n",
    "for i, num_att in enumerate(num_atts):\n",
    "\n",
    "    # 1: All alcohol patients\n",
    "    sns.histplot(data=bd,x=num_att,bins=15, hue='Situacion_tratamiento', stat='probability', common_norm=False, kde=True,\n",
    "                 line_kws={'lw': 5}, alpha = 0.4, ax=axs[i, 0])\n",
    "    axs[i, 0].set_title(f\"\\nDistr. of {num_att}  - ALL\")\n",
    "\n",
    "    # 2: PRE\n",
    "    sns.histplot(data=conj_pre,x=num_att,bins=15, hue='Situacion_tratamiento', stat='probability', common_norm=False, kde=True, \n",
    "                 line_kws={'lw': 5}, alpha = 0.4, ax=axs[i, 1])\n",
    "    axs[i, 1].set_title(f\"\\nDistr. of {num_att}  - PRE\")\n",
    "\n",
    "    # Subplot 3: POST\n",
    "    sns.histplot(data=conj_post,x=num_att,bins=15, hue='Situacion_tratamiento', stat='probability', common_norm=False, kde=True, \n",
    "                 line_kws={'lw': 5}, alpha = 0.4, ax=axs[i, 2])\n",
    "    axs[i, 2].set_title(f\"\\nDistr. of {num_att}  - POST\")\n",
    "\n",
    "# Adjust layout to prevent overlapping titles\n",
    "plt.tight_layout()\n",
    "\n",
928 929
    "# Save the figure in SVG format with DPI=600 in the \"./EDA_plots\" folder\n",
    "plt.savefig('./EDA_plots/histograms.svg', dpi=600, bbox_inches='tight')"
Joaquin Torres's avatar
Joaquin Torres committed
930 931 932 933 934 935 936 937 938 939 940 941 942
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Correlation Analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
943
    "##### Turning binary variables into 0/1 values"
Joaquin Torres's avatar
Joaquin Torres committed
944 945 946 947
   ]
  },
  {
   "cell_type": "code",
948
   "execution_count": 15,
Joaquin Torres's avatar
Joaquin Torres committed
949 950 951
   "metadata": {},
   "outputs": [],
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Alterations_early_childhood_develop'\n",
    "alterations_mapping = {\n",
    "    'No alterations (first exposure at 11 or more years)' : 0,\n",
    "    'Alterations (first exposure before 11 years old)': 1,\n",
    "}\n",
    "\n",
    "bd['Alterations_early_childhood_develop_REDEF'] = bd['Alterations_early_childhood_develop'].map(alterations_mapping)\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# Social protection\n",
    "bd['Social_protection_REDEF'] = bd['Social_protection'].map({'No':0, 'Sí':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Risk_stigma'\n",
    "bd['Risk_stigma_REDEF'] = bd['Risk_stigma'].map({'No':0, 'Yes':1})\n",
    "\n",
Joaquin Torres's avatar
Joaquin Torres committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Sex'\n",
    "bd['Sex_REDEF'] = bd['Sex'].map({'Hombre':0, 'Mujer':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Smoking'\n",
    "bd['Smoking_REDEF'] = bd['Smoking'].map({'No':0, 'Sí':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Biological_vulnerability'\n",
    "bd['Biological_vulnerability_REDEF'] = bd['Biological_vulnerability'].map({'No':0, 'Sí':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Droga_DxCIE'\n",
    "bd['Opiaceos_DxCIE_REDEF'] = bd['Opiaceos_DxCIE'].map({'No': 0, 'Sí': 1})\n",
    "bd['Cannabis_DXCIE_REDEF'] = bd['Cannabis_DXCIE'].map({'No': 0, 'Sí': 1})\n",
    "bd['BZD_DxCIE_REDEF'] = bd['BZD_DxCIE'].map({'No': 0, 'Sí': 1})\n",
    "bd['Cocaina_DxCIE_REDEF'] = bd['Cocaina_DxCIE'].map({'No': 0, 'Sí': 1})\n",
    "bd['Alucinogenos_DXCIE_REDEF'] = bd['Alucinogenos_DXCIE'].map({'No': 0, 'Sí': 1})\n",
    "bd['Tabaco_DXCIE_REDEF'] = bd['Tabaco_DXCIE'].map({'No': 0, 'Sí': 1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'OtrosDx_Psiquiatrico'\n",
    "bd['OtrosDx_Psiquiatrico_REDEF'] = bd['OtrosDx_Psiquiatrico'].map({'No':0, 'Sí':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
    "# 'Tx_previos'\n",
    "bd['Tx_previos_REDEF'] = bd['Tx_previos'].map({'No':0, 'Sí':1})\n",
    "\n",
    "# --------------------------------------------------------------------------\n",
    "\n",
1009 1010 1011
    "# 'Situacion_tratamiento (!!!!!)\n",
    "# Important to define properly\n",
    "bd['Situacion_tratamiento_REDEF'] = bd['Situacion_tratamiento'].map({'Abandono':1, 'Alta terapéutica':0})\n",
Joaquin Torres's avatar
Joaquin Torres committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    "\n",
    "# --------------------------------------------------------------------------"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Defining groups of variables"
   ]
  },
  {
   "cell_type": "code",
1025
   "execution_count": 16,
Joaquin Torres's avatar
Joaquin Torres committed
1026 1027 1028 1029 1030
   "metadata": {},
   "outputs": [],
   "source": [
    "social_vars = ['Education', 'Social_protection', 'Job_insecurity', 'Housing', 'Alterations_early_childhood_develop', \n",
    "            'Social_inclusion', 'Risk_stigma', 'Structural_conflic']\n",
1031 1032 1033
    "ind_vars = ['Age', 'Sex', 'NumHijos', 'Smoking', 'Biological_vulnerability', 'Opiaceos_DxCIE', \n",
    "            'Cannabis_DXCIE', 'BZD_DxCIE', 'Cocaina_DxCIE', 'Alucinogenos_DXCIE', 'Tabaco_DXCIE', \n",
    "            'FrecuenciaConsumo30Dias', 'Años_consumo_droga','OtrosDx_Psiquiatrico', 'Tx_previos', 'Adherencia_tto_recalc'] \n",
1034
    "target_var = 'Situacion_tratamiento'"
Joaquin Torres's avatar
Joaquin Torres committed
1035 1036 1037 1038
   ]
  },
  {
   "cell_type": "code",
1039
   "execution_count": 17,
Joaquin Torres's avatar
Joaquin Torres committed
1040 1041 1042 1043
   "metadata": {},
   "outputs": [],
   "source": [
    "# Columns that are already numeric and we don't need to redefine \n",
1044
    "no_redef_cols = ['Structural_conflic', 'Age', 'NumHijos', 'Años_consumo_droga', 'Adherencia_tto_recalc']"
Joaquin Torres's avatar
Joaquin Torres committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# res_vars = ['Tiempo_tx', 'Readmisiones_estudios', 'Periodos_COVID', 'Pandemia_inicio_fin_tratamiento', \n",
    "#            'Nreadmision', 'Readmisiones_PRECOVID', 'Readmisiones_COVID']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1061
    "##### One-hot encode categorical variables"
Joaquin Torres's avatar
Joaquin Torres committed
1062 1063 1064 1065
   ]
  },
  {
   "cell_type": "code",
1066
   "execution_count": 18,
1067 1068
   "metadata": {},
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
1069 1070
   "source": [
    "# Specify columns to one hot encode; empty list otherwise\n",
1071
    "one_hot_vars = ['Education', 'Job_insecurity', 'Housing', 'Social_inclusion', 'FrecuenciaConsumo30Dias']\n",
Joaquin Torres's avatar
Joaquin Torres committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    "\n",
    "one_hots_vars_prefix = {\n",
    "    'Education': 'Ed',\n",
    "    'Job_insecurity': 'JobIn',\n",
    "    'Housing': 'Hous', \n",
    "    'Social_inclusion': 'SocInc',\n",
    "    'FrecuenciaConsumo30Dias': 'Frec30',\n",
    "}\n",
    "\n",
    "one_hot_cols_dic = {}\n",
    "\n",
    "for one_hot_var in one_hot_vars:\n",
    "    # Create one hot encoding version of attribute and concatenate new columns to main df\n",
    "    encoded_var = pd.get_dummies(bd[one_hot_var], prefix=one_hots_vars_prefix[one_hot_var])\n",
    "    bd = pd.concat([bd, encoded_var], axis=1)\n",
    "    one_hot_cols_dic[one_hot_var] = encoded_var.columns.tolist()\n",
    "\n",
1089
    "# print(one_hot_cols_dic['FrecuenciaConsumo30Dias'])"
Joaquin Torres's avatar
Joaquin Torres committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Defining final version of columns of interest"
   ]
  },
  {
   "cell_type": "code",
1101
   "execution_count": 19,
Joaquin Torres's avatar
Joaquin Torres committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
   "metadata": {},
   "outputs": [],
   "source": [
    "soc_vars_enc = []\n",
    "for soc_var in social_vars:\n",
    "    # If no need to redefine, append directly\n",
    "    if soc_var in no_redef_cols:\n",
    "        soc_vars_enc.append(soc_var)\n",
    "    # If need to redefine\n",
    "    else:\n",
    "        # Check if it was one-hot encoded\n",
    "        if soc_var in one_hot_vars:\n",
    "            # Append all one hot columns\n",
    "            soc_vars_enc = soc_vars_enc + one_hot_cols_dic[soc_var]\n",
    "        # If not, use redefined version through mapping\n",
    "        else:\n",
    "            soc_vars_enc.append(soc_var + '_REDEF')\n",
    "\n",
    "ind_vars_enc = []\n",
    "for ind_var in ind_vars:\n",
    "    # If no need to redefine, append directly\n",
    "    if ind_var in no_redef_cols:\n",
    "        ind_vars_enc.append(ind_var)\n",
    "    # If need to redefine\n",
    "    else:\n",
    "        # Check if it was one-hot encoded\n",
    "        if ind_var in one_hot_vars:\n",
    "            # Append all one hot columns\n",
    "            ind_vars_enc = ind_vars_enc + one_hot_cols_dic[ind_var]\n",
    "        # If not, use redefined version through mapping\n",
    "        else:\n",
    "            ind_vars_enc.append(ind_var + '_REDEF')\n",
    "\n",
    "# Final version of columns we need to use for correlation analysis\n",
    "corr_cols = soc_vars_enc + ind_vars_enc"
   ]
  },
  {
Joaquin Torres's avatar
Joaquin Torres committed
1140
   "cell_type": "markdown",
Joaquin Torres's avatar
Joaquin Torres committed
1141 1142
   "metadata": {},
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1143
    "###### Update main data frames"
Joaquin Torres's avatar
Joaquin Torres committed
1144 1145 1146 1147
   ]
  },
  {
   "cell_type": "code",
1148
   "execution_count": 20,
Joaquin Torres's avatar
Joaquin Torres committed
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pre-pandemic\n",
    "conj_pre = bd[bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio y fin prepandemia']\n",
    "# Pre-pandemic abandono\n",
    "pre_abandono = conj_pre[conj_pre['Situacion_tratamiento'] == 'Abandono']\n",
    "# Pre-pandemic alta\n",
    "pre_alta = conj_pre[conj_pre['Situacion_tratamiento'] == 'Alta terapéutica']\n",
    "\n",
    "# Post-pandemic\n",
    "# Merging last two classes to balance sets\n",
    "conj_post = bd[(bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio prepandemia y fin en pandemia') | \n",
    "               (bd['Pandemia_inicio_fin_tratamiento'] == 'inicio y fin en pandemia')]\n",
    "# Post-pandemic abandono\n",
    "post_abandono = conj_post[conj_post['Situacion_tratamiento'] == 'Abandono']\n",
    "# Post-pandemic alta\n",
    "post_alta = conj_post[conj_post['Situacion_tratamiento'] == 'Alta terapéutica']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1173 1174 1175 1176 1177
    "##### Building correlation matrix"
   ]
  },
  {
   "cell_type": "code",
1178
   "execution_count": 21,
1179 1180 1181 1182 1183 1184 1185 1186 1187
   "metadata": {},
   "outputs": [],
   "source": [
    "binary_vars = [col for col in corr_cols if len(bd[col].unique()) == 2] + ['Situacion_tratamiento_REDEF', 'Risk_stigma_REDEF']\n",
    "cont_vars = ['Structural_conflic', 'Age', 'NumHijos', 'Años_consumo_droga', 'Adherencia_tto_recalc']"
   ]
  },
  {
   "cell_type": "code",
1188
   "execution_count": 22,
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_corr_matrix(df, cols):\n",
    "    \n",
    "    # Initialize nxn matrix to zeroes\n",
    "    n = len(cols)\n",
    "    corr_matrix = np.zeros((n,n))\n",
    "\n",
    "    for i, var_i in enumerate(cols):\n",
    "        for j, var_j in enumerate(cols):\n",
1200
    "            # Fill lower triangle of matrix\n",
1201 1202 1203 1204 1205
    "            if i > j:\n",
    "                # Binary with binary correlation: tetrachoric\n",
    "                if var_i in binary_vars and var_j in binary_vars:\n",
    "                    corr = binary_binary(df[var_i], df[var_j], measure='tetrachoric')\n",
    "                # Continuous with continuous correlation: \n",
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    "                elif var_i in cont_vars and var_j in cont_vars:\n",
    "                    # Returning nan sometimes:\n",
    "                    # corr_tuple = continuous_continuous(df[var_i], df[var_j], measure = 'spearman')\n",
    "                    # corr = corr_tuple[0]\n",
    "                    corr = df[var_i].corr(df[var_j], method='spearman')\n",
    "                # Binary vs Continuous correlation:\n",
    "                else:\n",
    "                    if var_i in binary_vars:\n",
    "                        bin_var = var_i\n",
    "                        cont_var = var_j\n",
    "                    else:\n",
    "                        bin_var = var_j\n",
    "                        cont_var = var_i\n",
1219
    "                    corr = binary_continuous(df[bin_var], df[cont_var], measure='point_biserial')\n",
1220 1221 1222 1223
    "                # Assign value to matrix\n",
    "                corr_matrix[i][j] = corr \n",
    "                      \n",
    "    return corr_matrix"
Joaquin Torres's avatar
Joaquin Torres committed
1224 1225 1226 1227
   ]
  },
  {
   "cell_type": "code",
1228
   "execution_count": 23,
Joaquin Torres's avatar
Joaquin Torres committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_heatmap(sit_tto: int, group:int) -> None:\n",
    "    \"\"\"\n",
    "        sit_tto: 1 (include it as another var), 2 (only abandono), 3 (only alta)\n",
    "        group: 1 (all alcohol patients), 2 (pre), 3 (post)\n",
    "    \"\"\"\n",
    "\n",
    "    # Define columns based on sit_tto arg\n",
    "    if sit_tto == 1:\n",
    "        # Include target as another variable\n",
    "        cols = [target_var + '_REDEF'] + corr_cols\n",
    "    else:\n",
    "        cols = corr_cols\n",
    "        \n",
    "    # Title plot and select datat based on group and sit_tto\n",
    "    if group == 1:\n",
    "        plot_title = \"Correl Matrix - ALL\"\n",
    "        if sit_tto == 1:\n",
    "            bd_ca = bd[cols]\n",
    "        elif sit_tto == 2:\n",
    "            bd_ca = bd[bd['Situacion_tratamiento'] == 'Abandono'][cols]\n",
    "        elif sit_tto == 3:\n",
    "            bd_ca = bd[bd['Situacion_tratamiento'] == 'Alta terapéutica'][cols]\n",
    "    elif group == 2:\n",
    "        plot_title = \"Correl Matrix - PRE\"\n",
    "        if sit_tto == 1:    \n",
    "            bd_ca = conj_pre[cols]\n",
    "        elif sit_tto == 2:\n",
    "            bd_ca = pre_abandono[cols]\n",
    "        elif sit_tto == 3:\n",
    "            bd_ca = pre_alta[cols]\n",
    "    elif group == 3:\n",
    "        plot_title = \"Correl Matrix - POST\"\n",
    "        if sit_tto == 1:    \n",
    "            bd_ca = conj_post[cols]\n",
    "        elif sit_tto == 2:\n",
    "            bd_ca = post_abandono[cols]\n",
    "        elif sit_tto == 3:\n",
    "            bd_ca = post_alta[cols]\n",
    "            \n",
    "    # Complete title\n",
    "    if sit_tto == 2:\n",
    "        plot_title += \" - ABANDONO\"\n",
    "    elif sit_tto == 3:\n",
    "        plot_title += \" - ALTA\"\n",
    "\n",
1277
    "    corr_matrix = get_corr_matrix(bd_ca, cols)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    "\n",
    "    # Create a mask for the upper triangle\n",
    "    mask = np.triu(np.ones_like(corr_matrix, dtype=bool))\n",
    "\n",
    "    # Create heatmap correlation matrix\n",
    "    dataplot = sns.heatmap(corr_matrix, mask=mask, xticklabels=cols, yticklabels=cols, cmap=\"coolwarm\", vmin=-1, vmax=1, annot=True, fmt=\".2f\", annot_kws={\"size\": 4})\n",
    "\n",
    "    # Group ind vs social vars by color and modify tick label names\n",
    "    for tick_label in dataplot.axes.xaxis.get_ticklabels():\n",
    "        if tick_label.get_text() in ind_vars_enc:\n",
    "            tick_label.set_color('green')\n",
    "        elif tick_label.get_text() in soc_vars_enc:\n",
    "            tick_label.set_color('purple')  \n",
    "    for tick_label in dataplot.axes.yaxis.get_ticklabels():\n",
    "        if tick_label.get_text() in ind_vars_enc:\n",
    "            tick_label.set_color('green')\n",
    "        elif tick_label.get_text() in soc_vars_enc:\n",
    "            tick_label.set_color('purple') \n",
    "\n",
    "    # Increase the size of xtick labels\n",
    "    # dataplot.tick_params(axis='x', labelsize=12)\n",
    "\n",
    "    # Increase the size of ytick labels\n",
    "    # dataplot.tick_params(axis='y', labelsize=12)\n",
    "\n",
    "    # Add legend and place it in lower left \n",
    "    plt.legend(handles=[\n",
    "        plt.Line2D([0], [0], marker='o', color='w', label='Social Factors', markerfacecolor='purple', markersize=10),\n",
    "        plt.Line2D([0], [0], marker='o', color='w', label='Individual Factors', markerfacecolor='green', markersize=10)\n",
    "    ], bbox_to_anchor=(-0.1, -0.1), fontsize = 20)\n",
    "\n",
1309 1310 1311
    "    plt.title(\"\\n\\n\" + plot_title, fontdict={'fontsize': 30, 'fontweight': 'bold'})\n",
    "\n",
    "    return corr_matrix"
Joaquin Torres's avatar
Joaquin Torres committed
1312 1313 1314 1315
   ]
  },
  {
   "cell_type": "code",
Joaquin Torres's avatar
Joaquin Torres committed
1316
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
1317
   "metadata": {},
Joaquin Torres's avatar
Joaquin Torres committed
1318
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
1319 1320 1321
   "source": [
    "fig, axs = plt.subplots(3, 3, figsize=(50, 50))\n",
    "plt.subplots_adjust(hspace=0.75, wspace=2)\n",
1322
    "corr_mats = [] # List of tuples (m1, m2) to store the 3 pairs of matrices to compare (pre vs post)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1323 1324
    "\n",
    "# Go through possible values for 'Situacion_tratamiento' and 'Group'\n",
Joaquin Torres's avatar
Joaquin Torres committed
1325
    "for sit_tto in range(1,4):\n",
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    "    # ALL\n",
    "    plt.subplot(3, 3, 3*(sit_tto-1) + 1)  # Calculate the subplot position dynamically\n",
    "    _ = plot_heatmap(sit_tto, 1)\n",
    "    # PRE\n",
    "    plt.subplot(3, 3, 3*(sit_tto-1) + 2) \n",
    "    corr_matrix_pre = plot_heatmap(sit_tto, 2)\n",
    "    # POST\n",
    "    plt.subplot(3, 3, 3*(sit_tto-1) + 3)\n",
    "    corr_matrix_post = plot_heatmap(sit_tto, 3)\n",
    "\n",
    "    corr_mats.append((corr_matrix_pre, corr_matrix_post))\n",
Joaquin Torres's avatar
Joaquin Torres committed
1337 1338 1339 1340
    "        \n",
    "# Adjust layout to prevent overlapping titles\n",
    "plt.tight_layout()\n",
    "\n",
1341 1342
    "# Save the figure in SVG format in the \"./EDA_plots\" folder\n",
    "plt.savefig('./EDA_plots/heatmaps_one_hot.svg', dpi=550, bbox_inches='tight')"
Joaquin Torres's avatar
Joaquin Torres committed
1343
   ]
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Finding significative differences between PRE and POST"
   ]
  },
  {
   "cell_type": "code",
Joaquin Torres's avatar
Joaquin Torres committed
1354
   "execution_count": null,
1355 1356 1357 1358
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_diff (sit_tto:int, m_pre, m_post):\n",
Joaquin Torres's avatar
Joaquin Torres committed
1359 1360 1361
    "\n",
    "    diff_list = []  # List to store tuples of (difference, variable_i, variable_j)\n",
    "\n",
1362 1363 1364 1365 1366 1367 1368 1369
    "    if sit_tto == 1:\n",
    "        cols = [target_var + '_REDEF'] + corr_cols\n",
    "    else:\n",
    "        cols = corr_cols\n",
    "    # Go through matrices\n",
    "    for i, var_i in enumerate(cols):\n",
    "        for j, var_j in enumerate(cols):\n",
    "            # If difference greater than certain threshold, print variables \n",
Joaquin Torres's avatar
Joaquin Torres committed
1370 1371 1372 1373 1374 1375 1376 1377 1378
    "            val_pre = m_pre[i][j]\n",
    "            val_post = m_post[i][j]\n",
    "            diff = abs(val_pre - val_post)\n",
    "            diff_list.append((diff, var_i, var_j, val_pre, val_post))\n",
    "    \n",
    "    # Sort the list based on the difference value in descending order\n",
    "    diff_list.sort(key=lambda x: x[0], reverse=True)\n",
    "            \n",
    "    # Print the sorted list\n",
1379
    "    for diff, var_i, var_j, val_pre, val_post in diff_list[0:100]:\n",
Joaquin Torres's avatar
Joaquin Torres committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    "        # Give ind vs soc vars their corresponding color\n",
    "        if var_i in ind_vars_enc:\n",
    "            print(colors.GREEN + var_i + colors.RESET, end=' ')\n",
    "        else:\n",
    "            print(colors.PURPLE + var_i + colors.PURPLE, end=' ')\n",
    "        print(\"& \", end='')\n",
    "        if var_j in ind_vars_enc:\n",
    "            print(colors.GREEN + var_j + colors.RESET, end=' ')\n",
    "        else:\n",
    "            print(colors.PURPLE + var_j + colors.RESET, end=' ')\n",
    "        print(f\"--> Diff: {diff:.2f} (PRE: {val_pre:.2f}; POST: {val_post:.2f})\")"
1391 1392 1393 1394
   ]
  },
  {
   "cell_type": "code",
Joaquin Torres's avatar
Joaquin Torres committed
1395
   "execution_count": null,
1396
   "metadata": {},
Joaquin Torres's avatar
Joaquin Torres committed
1397
   "outputs": [],
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
   "source": [
    "class colors:\n",
    "    RED = '\\033[91m'\n",
    "    GREEN = '\\033[92m'\n",
    "    YELLOW = '\\033[93m'\n",
    "    BLUE = '\\033[94m'\n",
    "    PURPLE = '\\033[95m'\n",
    "    CYAN = '\\033[96m'\n",
    "    WHITE = '\\033[97m'\n",
    "    RESET = '\\033[0m'\n",
    "\n",
    "# Print colored text\n",
    "print(colors.RED + \"This is red text.\" + colors.RESET)\n",
    "print(colors.GREEN + \"This is green text.\" + colors.RESET)\n",
    "print(colors.BLUE + \"This is blue text.\" + colors.RESET)"
1413 1414 1415 1416
   ]
  },
  {
   "cell_type": "code",
Joaquin Torres's avatar
Joaquin Torres committed
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
   "execution_count": null,
   "metadata": {
    "tags": [
     "keep"
    ]
   },
   "outputs": [],
   "source": [
    "print(\"------SIT_TTO 1: NO FILTERING------\")\n",
    "find_diff(1, corr_mats[0][0], corr_mats[0][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "keep"
    ]
   },
   "outputs": [],
   "source": [
    "print(\"------SIT_TTO 2: ABANDONO-----\")\n",
    "find_diff(2, corr_mats[1][0], corr_mats[1][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
1446 1447 1448 1449 1450
   "metadata": {
    "tags": [
     "keep"
    ]
   },
Joaquin Torres's avatar
Joaquin Torres committed
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
   "outputs": [],
   "source": [
    "print(\"------SIT_TTO 3: ALTA-----\")\n",
    "find_diff(3, corr_mats[2][0], corr_mats[2][1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Feature Analysis and Selection"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1468
    "##### Building final datasets to work with"
Joaquin Torres's avatar
Joaquin Torres committed
1469 1470 1471 1472
   ]
  },
  {
   "cell_type": "code",
1473
   "execution_count": 24,
Joaquin Torres's avatar
Joaquin Torres committed
1474
   "metadata": {},
Joaquin Torres's avatar
Joaquin Torres committed
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 33538 entries, 0 to 85164\n",
      "Data columns (total 45 columns):\n",
      " #   Column                                     Non-Null Count  Dtype   \n",
      "---  ------                                     --------------  -----   \n",
      " 0   Ed_Not Complete primary school             33538 non-null  bool    \n",
      " 1   Ed_Primary education                       33538 non-null  bool    \n",
      " 2   Ed_Secondary Education                     33538 non-null  bool    \n",
      " 3   Ed_Secondary more technical education      33538 non-null  bool    \n",
      " 4   Ed_Tertiary                                33538 non-null  bool    \n",
      " 5   Ed_Unknowledge                             33538 non-null  bool    \n",
      " 6   Social_protection_REDEF                    33538 non-null  int64   \n",
      " 7   JobIn_Non-stable                           33538 non-null  bool    \n",
      " 8   JobIn_Stable                               33538 non-null  bool    \n",
      " 9   JobIn_Unemployed                           33538 non-null  bool    \n",
      " 10  JobIn_unkwnodledge                         33538 non-null  bool    \n",
      " 11  Hous_Institutional                         33538 non-null  bool    \n",
      " 12  Hous_Stable                                33538 non-null  bool    \n",
      " 13  Hous_Unstable                              33538 non-null  bool    \n",
      " 14  Hous_unknowledge                           33538 non-null  bool    \n",
      " 15  Alterations_early_childhood_develop_REDEF  33538 non-null  int64   \n",
      " 16  SocInc_Live with families or friends       33538 non-null  bool    \n",
      " 17  SocInc_live alone                          33538 non-null  bool    \n",
      " 18  SocInc_live in institutions                33538 non-null  bool    \n",
      " 19  Risk_stigma_REDEF                          33538 non-null  category\n",
      " 20  Structural_conflic                         33538 non-null  float64 \n",
      " 21  Age                                        33538 non-null  float64 \n",
      " 22  Sex_REDEF                                  33538 non-null  int64   \n",
      " 23  NumHijos                                   33538 non-null  float64 \n",
      " 24  Smoking_REDEF                              33538 non-null  int64   \n",
      " 25  Biological_vulnerability_REDEF             33538 non-null  int64   \n",
      " 26  Opiaceos_DxCIE_REDEF                       33538 non-null  int64   \n",
      " 27  Cannabis_DXCIE_REDEF                       33538 non-null  int64   \n",
      " 28  BZD_DxCIE_REDEF                            33538 non-null  int64   \n",
      " 29  Cocaina_DxCIE_REDEF                        33538 non-null  int64   \n",
      " 30  Alucinogenos_DXCIE_REDEF                   33538 non-null  int64   \n",
      " 31  Tabaco_DXCIE_REDEF                         33538 non-null  int64   \n",
      " 32  Frec30_1 día/semana                        33538 non-null  bool    \n",
      " 33  Frec30_2-3 días‎/semana                    33538 non-null  bool    \n",
      " 34  Frec30_4-6 días/semana                     33538 non-null  bool    \n",
      " 35  Frec30_Desconocido                         33538 non-null  bool    \n",
      " 36  Frec30_Menos de 1 día‎/semana              33538 non-null  bool    \n",
      " 37  Frec30_No consumio                         33538 non-null  bool    \n",
      " 38  Frec30_Todos los días                      33538 non-null  bool    \n",
      " 39  Años_consumo_droga                         33538 non-null  float64 \n",
      " 40  OtrosDx_Psiquiatrico_REDEF                 33538 non-null  int64   \n",
      " 41  Tx_previos_REDEF                           33538 non-null  int64   \n",
      " 42  Adherencia_tto_recalc                      33538 non-null  float64 \n",
      " 43  Pandemia_inicio_fin_tratamiento            33538 non-null  object  \n",
      " 44  Situacion_tratamiento_REDEF                33538 non-null  int64   \n",
      "dtypes: bool(24), category(1), float64(5), int64(14), object(1)\n",
      "memory usage: 6.2+ MB\n",
      "None\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
1536 1537 1538 1539 1540 1541 1542 1543 1544
   "source": [
    "# Work with columns of interest\n",
    "cols_of_interest = corr_cols + ['Pandemia_inicio_fin_tratamiento'] + [target_var + \"_REDEF\"]\n",
    "temp_bd = bd[cols_of_interest]\n",
    "print(temp_bd.info()) # NaN values already dealt with (replaced by mode - this okay?)"
   ]
  },
  {
   "cell_type": "code",
1545
   "execution_count": 25,
Joaquin Torres's avatar
Joaquin Torres committed
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dropping unknown columns/categories for analysis purposes\n",
    "unknown_cols = ['Ed_Unknowledge', 'JobIn_unkwnodledge', 'Hous_unknowledge', 'Frec30_Desconocido']\n",
    "temp_bd = temp_bd.drop(columns=unknown_cols)"
   ]
  },
  {
   "cell_type": "code",
1556
   "execution_count": 26,
Joaquin Torres's avatar
Joaquin Torres committed
1557
   "metadata": {},
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 33538 entries, 0 to 85164\n",
      "Data columns (total 41 columns):\n",
      " #   Column                                     Non-Null Count  Dtype   \n",
      "---  ------                                     --------------  -----   \n",
      " 0   Ed_Not Complete primary school             33538 non-null  bool    \n",
      " 1   Ed_Primary education                       33538 non-null  bool    \n",
      " 2   Ed_Secondary Education                     33538 non-null  bool    \n",
      " 3   Ed_Secondary more technical education      33538 non-null  bool    \n",
      " 4   Ed_Tertiary                                33538 non-null  bool    \n",
      " 5   Social_protection_REDEF                    33538 non-null  int64   \n",
      " 6   JobIn_Non-stable                           33538 non-null  bool    \n",
      " 7   JobIn_Stable                               33538 non-null  bool    \n",
      " 8   JobIn_Unemployed                           33538 non-null  bool    \n",
      " 9   Hous_Institutional                         33538 non-null  bool    \n",
      " 10  Hous_Stable                                33538 non-null  bool    \n",
      " 11  Hous_Unstable                              33538 non-null  bool    \n",
      " 12  Alterations_early_childhood_develop_REDEF  33538 non-null  int64   \n",
      " 13  SocInc_Live with families or friends       33538 non-null  bool    \n",
      " 14  SocInc_live alone                          33538 non-null  bool    \n",
      " 15  SocInc_live in institutions                33538 non-null  bool    \n",
      " 16  Risk_stigma_REDEF                          33538 non-null  category\n",
      " 17  Structural_conflic                         33538 non-null  float64 \n",
      " 18  Age                                        33538 non-null  float64 \n",
      " 19  Sex_REDEF                                  33538 non-null  int64   \n",
      " 20  NumHijos                                   33538 non-null  float64 \n",
      " 21  Smoking_REDEF                              33538 non-null  int64   \n",
      " 22  Biological_vulnerability_REDEF             33538 non-null  int64   \n",
      " 23  Opiaceos_DxCIE_REDEF                       33538 non-null  int64   \n",
      " 24  Cannabis_DXCIE_REDEF                       33538 non-null  int64   \n",
      " 25  BZD_DxCIE_REDEF                            33538 non-null  int64   \n",
      " 26  Cocaina_DxCIE_REDEF                        33538 non-null  int64   \n",
      " 27  Alucinogenos_DXCIE_REDEF                   33538 non-null  int64   \n",
      " 28  Tabaco_DXCIE_REDEF                         33538 non-null  int64   \n",
      " 29  Frec30_1 día/semana                        33538 non-null  bool    \n",
      " 30  Frec30_2-3 días‎/semana                    33538 non-null  bool    \n",
      " 31  Frec30_4-6 días/semana                     33538 non-null  bool    \n",
      " 32  Frec30_Menos de 1 día‎/semana              33538 non-null  bool    \n",
      " 33  Frec30_No consumio                         33538 non-null  bool    \n",
      " 34  Frec30_Todos los días                      33538 non-null  bool    \n",
      " 35  Años_consumo_droga                         33538 non-null  float64 \n",
      " 36  OtrosDx_Psiquiatrico_REDEF                 33538 non-null  int64   \n",
      " 37  Tx_previos_REDEF                           33538 non-null  int64   \n",
      " 38  Adherencia_tto_recalc                      33538 non-null  float64 \n",
      " 39  Pandemia_inicio_fin_tratamiento            33538 non-null  object  \n",
      " 40  Situacion_tratamiento_REDEF                33538 non-null  int64   \n",
      "dtypes: bool(20), category(1), float64(5), int64(14), object(1)\n",
      "memory usage: 6.0+ MB\n",
      "None\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
1615 1616 1617 1618 1619 1620
   "source": [
    "print(temp_bd.info())"
   ]
  },
  {
   "cell_type": "code",
1621
   "execution_count": 27,
Joaquin Torres's avatar
Joaquin Torres committed
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
   "metadata": {},
   "outputs": [],
   "source": [
    "# For conj_pre dataframe\n",
    "conj_pre = temp_bd[temp_bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio y fin prepandemia']\n",
    "conj_pre = conj_pre.drop(columns=['Pandemia_inicio_fin_tratamiento'])\n",
    "\n",
    "# For conj_post dataframe\n",
    "conj_post = temp_bd[(temp_bd['Pandemia_inicio_fin_tratamiento'] == 'Inicio prepandemia y fin en pandemia') | \n",
    "                    (temp_bd['Pandemia_inicio_fin_tratamiento'] == 'inicio y fin en pandemia')]\n",
    "conj_post = conj_post.drop(columns=['Pandemia_inicio_fin_tratamiento'])"
   ]
  },
  {
   "cell_type": "code",
1637
   "execution_count": 28,
Joaquin Torres's avatar
Joaquin Torres committed
1638
   "metadata": {},
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 22861 entries, 0 to 85164\n",
      "Data columns (total 40 columns):\n",
      " #   Column                                     Non-Null Count  Dtype   \n",
      "---  ------                                     --------------  -----   \n",
      " 0   Ed_Not Complete primary school             22861 non-null  bool    \n",
      " 1   Ed_Primary education                       22861 non-null  bool    \n",
      " 2   Ed_Secondary Education                     22861 non-null  bool    \n",
      " 3   Ed_Secondary more technical education      22861 non-null  bool    \n",
      " 4   Ed_Tertiary                                22861 non-null  bool    \n",
      " 5   Social_protection_REDEF                    22861 non-null  int64   \n",
      " 6   JobIn_Non-stable                           22861 non-null  bool    \n",
      " 7   JobIn_Stable                               22861 non-null  bool    \n",
      " 8   JobIn_Unemployed                           22861 non-null  bool    \n",
      " 9   Hous_Institutional                         22861 non-null  bool    \n",
      " 10  Hous_Stable                                22861 non-null  bool    \n",
      " 11  Hous_Unstable                              22861 non-null  bool    \n",
      " 12  Alterations_early_childhood_develop_REDEF  22861 non-null  int64   \n",
      " 13  SocInc_Live with families or friends       22861 non-null  bool    \n",
      " 14  SocInc_live alone                          22861 non-null  bool    \n",
      " 15  SocInc_live in institutions                22861 non-null  bool    \n",
      " 16  Risk_stigma_REDEF                          22861 non-null  category\n",
      " 17  Structural_conflic                         22861 non-null  float64 \n",
      " 18  Age                                        22861 non-null  float64 \n",
      " 19  Sex_REDEF                                  22861 non-null  int64   \n",
      " 20  NumHijos                                   22861 non-null  float64 \n",
      " 21  Smoking_REDEF                              22861 non-null  int64   \n",
      " 22  Biological_vulnerability_REDEF             22861 non-null  int64   \n",
      " 23  Opiaceos_DxCIE_REDEF                       22861 non-null  int64   \n",
      " 24  Cannabis_DXCIE_REDEF                       22861 non-null  int64   \n",
      " 25  BZD_DxCIE_REDEF                            22861 non-null  int64   \n",
      " 26  Cocaina_DxCIE_REDEF                        22861 non-null  int64   \n",
      " 27  Alucinogenos_DXCIE_REDEF                   22861 non-null  int64   \n",
      " 28  Tabaco_DXCIE_REDEF                         22861 non-null  int64   \n",
      " 29  Frec30_1 día/semana                        22861 non-null  bool    \n",
      " 30  Frec30_2-3 días‎/semana                    22861 non-null  bool    \n",
      " 31  Frec30_4-6 días/semana                     22861 non-null  bool    \n",
      " 32  Frec30_Menos de 1 día‎/semana              22861 non-null  bool    \n",
      " 33  Frec30_No consumio                         22861 non-null  bool    \n",
      " 34  Frec30_Todos los días                      22861 non-null  bool    \n",
      " 35  Años_consumo_droga                         22861 non-null  float64 \n",
      " 36  OtrosDx_Psiquiatrico_REDEF                 22861 non-null  int64   \n",
      " 37  Tx_previos_REDEF                           22861 non-null  int64   \n",
      " 38  Adherencia_tto_recalc                      22861 non-null  float64 \n",
      " 39  Situacion_tratamiento_REDEF                22861 non-null  int64   \n",
      "dtypes: bool(20), category(1), float64(5), int64(14)\n",
      "memory usage: 3.9 MB\n",
      "None\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
1695
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1696
    "print(conj_pre.info())"
Joaquin Torres's avatar
Joaquin Torres committed
1697 1698 1699 1700
   ]
  },
  {
   "cell_type": "code",
1701
   "execution_count": 29,
Joaquin Torres's avatar
Joaquin Torres committed
1702
   "metadata": {},
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 10677 entries, 11 to 85156\n",
      "Data columns (total 40 columns):\n",
      " #   Column                                     Non-Null Count  Dtype   \n",
      "---  ------                                     --------------  -----   \n",
      " 0   Ed_Not Complete primary school             10677 non-null  bool    \n",
      " 1   Ed_Primary education                       10677 non-null  bool    \n",
      " 2   Ed_Secondary Education                     10677 non-null  bool    \n",
      " 3   Ed_Secondary more technical education      10677 non-null  bool    \n",
      " 4   Ed_Tertiary                                10677 non-null  bool    \n",
      " 5   Social_protection_REDEF                    10677 non-null  int64   \n",
      " 6   JobIn_Non-stable                           10677 non-null  bool    \n",
      " 7   JobIn_Stable                               10677 non-null  bool    \n",
      " 8   JobIn_Unemployed                           10677 non-null  bool    \n",
      " 9   Hous_Institutional                         10677 non-null  bool    \n",
      " 10  Hous_Stable                                10677 non-null  bool    \n",
      " 11  Hous_Unstable                              10677 non-null  bool    \n",
      " 12  Alterations_early_childhood_develop_REDEF  10677 non-null  int64   \n",
      " 13  SocInc_Live with families or friends       10677 non-null  bool    \n",
      " 14  SocInc_live alone                          10677 non-null  bool    \n",
      " 15  SocInc_live in institutions                10677 non-null  bool    \n",
      " 16  Risk_stigma_REDEF                          10677 non-null  category\n",
      " 17  Structural_conflic                         10677 non-null  float64 \n",
      " 18  Age                                        10677 non-null  float64 \n",
      " 19  Sex_REDEF                                  10677 non-null  int64   \n",
      " 20  NumHijos                                   10677 non-null  float64 \n",
      " 21  Smoking_REDEF                              10677 non-null  int64   \n",
      " 22  Biological_vulnerability_REDEF             10677 non-null  int64   \n",
      " 23  Opiaceos_DxCIE_REDEF                       10677 non-null  int64   \n",
      " 24  Cannabis_DXCIE_REDEF                       10677 non-null  int64   \n",
      " 25  BZD_DxCIE_REDEF                            10677 non-null  int64   \n",
      " 26  Cocaina_DxCIE_REDEF                        10677 non-null  int64   \n",
      " 27  Alucinogenos_DXCIE_REDEF                   10677 non-null  int64   \n",
      " 28  Tabaco_DXCIE_REDEF                         10677 non-null  int64   \n",
      " 29  Frec30_1 día/semana                        10677 non-null  bool    \n",
      " 30  Frec30_2-3 días‎/semana                    10677 non-null  bool    \n",
      " 31  Frec30_4-6 días/semana                     10677 non-null  bool    \n",
      " 32  Frec30_Menos de 1 día‎/semana              10677 non-null  bool    \n",
      " 33  Frec30_No consumio                         10677 non-null  bool    \n",
      " 34  Frec30_Todos los días                      10677 non-null  bool    \n",
      " 35  Años_consumo_droga                         10677 non-null  float64 \n",
      " 36  OtrosDx_Psiquiatrico_REDEF                 10677 non-null  int64   \n",
      " 37  Tx_previos_REDEF                           10677 non-null  int64   \n",
      " 38  Adherencia_tto_recalc                      10677 non-null  float64 \n",
      " 39  Situacion_tratamiento_REDEF                10677 non-null  int64   \n",
      "dtypes: bool(20), category(1), float64(5), int64(14)\n",
      "memory usage: 1.8 MB\n",
      "None\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
1759 1760 1761 1762 1763 1764
   "source": [
    "print(conj_post.info())"
   ]
  },
  {
   "cell_type": "code",
1765
   "execution_count": 35,
Joaquin Torres's avatar
Joaquin Torres committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
   "metadata": {},
   "outputs": [],
   "source": [
    "# Creating a numpy matrix without the target variable (X) and a list with the target variable (y) \n",
    "X_pre, y_pre = conj_pre.loc[:, conj_pre.columns != \"Situacion_tratamiento_REDEF\"].to_numpy(), conj_pre.Situacion_tratamiento_REDEF\n",
    "X_post, y_post = conj_post.loc[:, conj_post.columns != \"Situacion_tratamiento_REDEF\"].to_numpy(), conj_post.Situacion_tratamiento_REDEF\n",
    "feat = np.delete(conj_pre.columns.to_numpy(),-1) # Get labels and remove target "
   ]
  },
  {
   "cell_type": "code",
1777
   "execution_count": 36,
Joaquin Torres's avatar
Joaquin Torres committed
1778
   "metadata": {},
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Ed_Not Complete primary school' 'Ed_Primary education'\n",
      " 'Ed_Secondary Education' 'Ed_Secondary more technical education'\n",
      " 'Ed_Tertiary' 'Social_protection_REDEF' 'JobIn_Non-stable' 'JobIn_Stable'\n",
      " 'JobIn_Unemployed' 'Hous_Institutional' 'Hous_Stable' 'Hous_Unstable'\n",
      " 'Alterations_early_childhood_develop_REDEF'\n",
      " 'SocInc_Live with families or friends' 'SocInc_live alone'\n",
      " 'SocInc_live in institutions' 'Risk_stigma_REDEF' 'Structural_conflic'\n",
      " 'Age' 'Sex_REDEF' 'NumHijos' 'Smoking_REDEF'\n",
      " 'Biological_vulnerability_REDEF' 'Opiaceos_DxCIE_REDEF'\n",
      " 'Cannabis_DXCIE_REDEF' 'BZD_DxCIE_REDEF' 'Cocaina_DxCIE_REDEF'\n",
      " 'Alucinogenos_DXCIE_REDEF' 'Tabaco_DXCIE_REDEF' 'Frec30_1 día/semana'\n",
      " 'Frec30_2-3 días\\u200e/semana' 'Frec30_4-6 días/semana'\n",
      " 'Frec30_Menos de 1 día\\u200e/semana' 'Frec30_No consumio'\n",
      " 'Frec30_Todos los días' 'Años_consumo_droga' 'OtrosDx_Psiquiatrico_REDEF'\n",
      " 'Tx_previos_REDEF' 'Adherencia_tto_recalc']\n"
     ]
    }
   ],
Joaquin Torres's avatar
Joaquin Torres committed
1802
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1803
    "print(feat)"
Joaquin Torres's avatar
Joaquin Torres committed
1804 1805 1806 1807
   ]
  },
  {
   "cell_type": "code",
1808
   "execution_count": 37,
Joaquin Torres's avatar
Joaquin Torres committed
1809
   "metadata": {},
Joaquin Torres's avatar
Joaquin Torres committed
1810 1811 1812 1813 1814
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Joaquin Torres's avatar
Joaquin Torres committed
1815 1816 1817 1818 1819
      "(22861, 39)\n",
      "(10677, 39)\n",
      "(22861,)\n",
      "(10677,)\n",
      "39\n"
1820 1821 1822 1823
     ]
    }
   ],
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    "print(X_pre.shape)\n",
    "print(X_post.shape)\n",
    "print(y_pre.shape)\n",
    "print(y_post.shape)\n",
    "print(len(feat))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### FSS Filter methods"
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
1838 1839 1840 1841 1842 1843 1844
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### Mutual Info"
   ]
  },
Joaquin Torres's avatar
Joaquin Torres committed
1845 1846
  {
   "cell_type": "code",
1847
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
1848
   "metadata": {},
1849
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
1850
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1851 1852 1853 1854
    "# Create subplots\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 6))\n",
    "\n",
    "# PRE\n",
1855
    "importances_MI = mutual_info_classif(X_pre, y_pre)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1856 1857 1858 1859 1860
    "feat_importances_MI = pd.Series(importances_MI, feat)\n",
    "feat_importances_MI.sort_values(inplace=True)\n",
    "axes[0].barh(feat_importances_MI[feat_importances_MI != 0][-20:].index, feat_importances_MI[feat_importances_MI != 0][-20:], color='teal')\n",
    "axes[0].set_xlabel(\"Mutual Information\")\n",
    "axes[0].set_title(\"PRE\")\n",
Joaquin Torres's avatar
Joaquin Torres committed
1861
    "\n",
Joaquin Torres's avatar
Joaquin Torres committed
1862
    "# POST\n",
1863
    "importances_MI = mutual_info_classif(X_post, y_post)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1864 1865
    "feat_importances_MI = pd.Series(importances_MI, feat)\n",
    "feat_importances_MI.sort_values(inplace=True)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1866 1867 1868
    "axes[1].barh(feat_importances_MI[feat_importances_MI != 0][-20:].index, feat_importances_MI[feat_importances_MI != 0][-20:], color='teal')\n",
    "axes[1].set_xlabel(\"Mutual Information\")\n",
    "axes[1].set_title(\"POST\")\n",
Joaquin Torres's avatar
Joaquin Torres committed
1869 1870
    "\n",
    "plt.tight_layout()\n",
Joaquin Torres's avatar
Joaquin Torres committed
1871
    "plt.savefig('EDA_plots/features/mutual_info.svg', format='svg', dpi=1200)\n",
1872
    "plt.show()"
Joaquin Torres's avatar
Joaquin Torres committed
1873 1874 1875 1876 1877 1878 1879
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### ANOVA"
Joaquin Torres's avatar
Joaquin Torres committed
1880 1881 1882 1883
   ]
  },
  {
   "cell_type": "code",
1884
   "execution_count": null,
Joaquin Torres's avatar
Joaquin Torres committed
1885
   "metadata": {},
1886
   "outputs": [],
Joaquin Torres's avatar
Joaquin Torres committed
1887
   "source": [
Joaquin Torres's avatar
Joaquin Torres committed
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    "# Create subplots\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 6))\n",
    "\n",
    "# PRE\n",
    "selector = SelectKBest(f_classif, k=39)\n",
    "selector.fit(X_pre, y_pre)\n",
    "feat_importances_AN_pre = pd.Series(selector.pvalues_, feat)\n",
    "feat_importances_AN_pre.sort_values(inplace=True)\n",
    "axes[0].barh(feat_importances_AN_pre[feat_importances_AN_pre > 0.005][-20:].index, feat_importances_AN_pre[feat_importances_AN_pre > 0.005][-20:], color='teal')\n",
    "axes[0].set_xlabel(\"p-value ANOVA\")\n",
    "axes[0].set_title(\"PRE\")\n",
    "\n",
    "# POST\n",
    "selector = SelectKBest(f_classif, k=39)\n",
    "selector.fit(X_post, y_post)\n",
1903
    "feat_importances_AN_post = pd.Series(selector.pvalues_, feat)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1904 1905 1906 1907
    "feat_importances_AN_post.sort_values(inplace=True)\n",
    "axes[1].barh(feat_importances_AN_post[feat_importances_AN_post > 0.005][-20:].index, feat_importances_AN_post[feat_importances_AN_post > 0.005][-20:], color='teal') \n",
    "axes[1].set_xlabel(\"p-value ANOVA\")\n",
    "axes[1].set_title(\"POST\")\n",
Joaquin Torres's avatar
Joaquin Torres committed
1908 1909
    "\n",
    "plt.tight_layout()\n",
Joaquin Torres's avatar
Joaquin Torres committed
1910
    "plt.savefig('EDA_plots/features/ANOVA.svg', format='svg', dpi=1200)\n",
Joaquin Torres's avatar
Joaquin Torres committed
1911
    "plt.show()"
1912
   ]
Joaquin Torres's avatar
Joaquin Torres committed
1913 1914 1915 1916 1917 1918
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
   "source": [
    "# Create subplots\n",
    "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
    "\n",
    "# PRE\n",
    "variance_filter = VarianceThreshold(threshold=0)\n",
    "variance_filter.fit(X_pre)\n",
    "feat_importances_var_pre = pd.Series(variance_filter.variances_, feat)\n",
    "feat_importances_var_pre.sort_values(inplace=True)\n",
    "axes[0].barh(feat_importances_var_pre[feat_importances_var_pre > 0.05][-20:].index, feat_importances_var_pre[feat_importances_var_pre > 0.05][-20:], color='teal')\n",
    "axes[0].set_xlabel(\"Variance\")\n",
    "axes[0].set_title(\"PRE\")\n",
    "\n",
    "# POST\n",
    "variance_filter = VarianceThreshold(threshold=0)\n",
    "variance_filter.fit(X_post)\n",
    "feat_importances_var_post = pd.Series(variance_filter.variances_, feat)\n",
    "feat_importances_var_post.sort_values(inplace=True)\n",
    "axes[1].barh(feat_importances_var_post[feat_importances_var_post > 0.05][-20:].index, feat_importances_var_post[feat_importances_var_post > 0.05][-20:], color='teal')\n",
    "axes[1].set_xlabel(\"Variance\")\n",
    "axes[1].set_title(\"POST\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.savefig('EDA_plots/features/var_threshold.svg', format='svg', dpi=1200)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Export PRE and POST datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "conj_pre.to_csv('pre_dataset.csv', index=False)\n",
    "conj_post.to_csv('post_dataset.csv', index=False)"
   ]
Joaquin Torres's avatar
Joaquin Torres committed
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}