{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":35332,"databundleVersionId":3723648,"sourceType":"competition"},{"sourceId":3739819,"sourceType":"datasetVersion","datasetId":2231132}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-21T23:42:01.498907Z","iopub.execute_input":"2024-10-21T23:42:01.499187Z","iopub.status.idle":"2024-10-21T23:42:02.501939Z","shell.execute_reply.started":"2024-10-21T23:42:01.499155Z","shell.execute_reply":"2024-10-21T23:42:02.501074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_raw = pd.read_parquet(\"../input/amex-data-integer-dtypes-parquet-format/train.parquet\")\n\nlabels = pd.read_csv('../input/amex-default-prediction/train_labels.csv')\n\n# Perform JOIN operation like SQL join. Here we have common attribute is 'customer_ID'\ntrain_raw = train_raw.merge(labels, left_on='customer_ID', right_on='customer_ID')","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:42:04.589513Z","iopub.execute_input":"2024-10-21T23:42:04.590490Z","iopub.status.idle":"2024-10-21T23:42:29.417320Z","shell.execute_reply.started":"2024-10-21T23:42:04.590450Z","shell.execute_reply":"2024-10-21T23:42:29.416189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_raw.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:42:34.565953Z","iopub.execute_input":"2024-10-21T23:42:34.566328Z","iopub.status.idle":"2024-10-21T23:42:34.596490Z","shell.execute_reply.started":"2024-10-21T23:42:34.566290Z","shell.execute_reply":"2024-10-21T23:42:34.595645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_raw.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:42:37.058155Z","iopub.execute_input":"2024-10-21T23:42:37.058529Z","iopub.status.idle":"2024-10-21T23:42:37.064454Z","shell.execute_reply.started":"2024-10-21T23:42:37.058491Z","shell.execute_reply":"2024-10-21T23:42:37.063612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We are gonna divide this whole dataset into 10 smaller parquet file\ndef divide_into_small_dataset(df, numOfFiles=10):\n    # We are dropping last row since 5531451 % 10 = 1. Because our dataset was too large so if we drop one row then it doesn't affect that much\n    chunkSize = train_raw.shape[0] // numOfFiles\n    \n    initialRow = 0\n    \n    i = 1\n\n    while i <= numOfFiles:\n        print(f\"File Number {i} contains rows from start={initialRow} and end={initialRow + chunkSize - 1}\")\n        \n        tmp = train_raw.iloc[initialRow: initialRow + chunkSize, :]\n\n        initialRow += chunkSize\n\n        tmp.to_parquet(f\"/kaggle/working/train_data_{i}.parquet\")\n        \n        i += 1","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:42:42.464459Z","iopub.execute_input":"2024-10-21T23:42:42.465329Z","iopub.status.idle":"2024-10-21T23:42:42.471236Z","shell.execute_reply.started":"2024-10-21T23:42:42.465288Z","shell.execute_reply":"2024-10-21T23:42:42.470146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"divide_into_small_dataset(train_raw)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:42:45.690234Z","iopub.execute_input":"2024-10-21T23:42:45.690583Z","iopub.status.idle":"2024-10-21T23:43:24.723665Z","shell.execute_reply.started":"2024-10-21T23:42:45.690550Z","shell.execute_reply":"2024-10-21T23:43:24.722665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Verifying the file last record with split end index\nfor i in range(1, 11):\n    train_raw_ith = pd.read_parquet(f\"/kaggle/working/train_data_{i}.parquet\")\n    \n    print(train_raw_ith.iloc[-1: , 0:1])","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:43:41.390866Z","iopub.execute_input":"2024-10-21T23:43:41.391221Z","iopub.status.idle":"2024-10-21T23:43:46.135359Z","shell.execute_reply.started":"2024-10-21T23:43:41.391186Z","shell.execute_reply":"2024-10-21T23:43:46.134384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df1 = pd.read_parquet(\"/kaggle/working/train_data_1.parquet\")\ndf2 = pd.read_parquet(\"/kaggle/working/train_data_2.parquet\")\n\nprev = df1.isna().sum().sort_values(ascending=False)\ncurr = df2.isna().sum().sort_values(ascending=False)\n\ncurr = curr + prev\n\nfor i in range(3, 11):\n    train_raw_ith = pd.read_parquet(f\"/kaggle/working/train_data_{i}.parquet\")\n    \n    tmp = train_raw_ith.isna().sum().sort_values(ascending=False)\n    \n    curr = curr + prev\n    \nnullValueCountPerCol = curr.div(len(train_raw) - 1).mul(100).sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:43:50.977490Z","iopub.execute_input":"2024-10-21T23:43:50.977890Z","iopub.status.idle":"2024-10-21T23:43:57.675128Z","shell.execute_reply.started":"2024-10-21T23:43:50.977850Z","shell.execute_reply":"2024-10-21T23:43:57.674307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:44:14.349904Z","iopub.execute_input":"2024-10-21T23:44:14.350601Z","iopub.status.idle":"2024-10-21T23:44:15.108967Z","shell.execute_reply.started":"2024-10-21T23:44:14.350557Z","shell.execute_reply":"2024-10-21T23:44:15.108182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(2,1, figsize=(35,20))\nsns.barplot(x=nullValueCountPerCol[:100].index, y=nullValueCountPerCol[:100].values, ax=ax[0])\nsns.barplot(x=nullValueCountPerCol[100:].index, y=nullValueCountPerCol[100:].values, ax=ax[1])\nax[0].set_ylabel(\"Percentage [%]\"), ax[1].set_ylabel(\"Percentage [%]\")\nax[0].tick_params(axis='x', rotation=90); ax[1].tick_params(axis='x', rotation=90)\nplt.suptitle(\"Amount of missing data\")\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:44:16.951293Z","iopub.execute_input":"2024-10-21T23:44:16.952173Z","iopub.status.idle":"2024-10-21T23:44:19.481394Z","shell.execute_reply.started":"2024-10-21T23:44:16.952130Z","shell.execute_reply":"2024-10-21T23:44:19.480300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"# of Non N/A columns: {nullValueCountPerCol[nullValueCountPerCol > 0.0].count()}\")\nprint(\"Top 20 features with highest number of values\")\nnullValueCountPerCol.head(50)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:44:22.123296Z","iopub.execute_input":"2024-10-21T23:44:22.124329Z","iopub.status.idle":"2024-10-21T23:44:22.137748Z","shell.execute_reply.started":"2024-10-21T23:44:22.124263Z","shell.execute_reply":"2024-10-21T23:44:22.136784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.impute import KNNImputer\n\ndef handleMissingValues():\n    colsGreaterThanEightyPercent = list(nullValueCountPerCol[nullValueCountPerCol > 80.00].index)\n    colsWithMissingValues = list(nullValueCountPerCol[nullValueCountPerCol > 0.00].index)\n    \n    imputer = KNNImputer(n_neighbors=2)\n    \n    for i in range(1, 11):\n        df = pd.read_parquet(f\"/kaggle/working/train_data_{i}.parquet\").drop(labels=colsGreaterThanEightyPercent, axis=1)\n\n        dCols = [col for col in df.columns if col.startswith('D_') and col in colsWithMissingValues]\n        dfContainsDColumns = df[dCols]\n        df.drop(labels=dCols, axis=1)\n        \n#         print(len(dCols))\n        \n        \n        # Execute KNN Imputer to handle missing values for 'D_' columns\n        dfContainsDColumns[:] = imputer.fit_transform(dfContainsDColumns)\n        \n        for col in df.columns:\n            if col in colsWithMissingValues:\n                if not col.startswith('D_'):\n                    df[col] = df[col].fillna(df[col].mean())\n                    \n        df = pd.concat([df, dfContainsDColumns], axis=1)\n                \n                \n        print(df)\n        \n# handleMissingValues()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T23:54:48.620758Z","iopub.execute_input":"2024-10-21T23:54:48.621138Z","iopub.status.idle":"2024-10-22T00:05:40.277503Z","shell.execute_reply.started":"2024-10-21T23:54:48.621102Z","shell.execute_reply":"2024-10-22T00:05:40.276137Z"},"trusted":true},"execution_count":null,"outputs":[]}]}