{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Save your Ram!\n\nThe point of the competition is to work with categorical data. However, pandas automatically reads any string column as a `dtype = object` column, which is notoriously inefficient. However, pandas' own `dtype`, `category`, can help us to save any column. "},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \n\ntrain_raw = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/train.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's confirm that pandas is reading the categorical columns as object dtypes. "},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_raw.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"There are 17 columns with `dtype` `object`. These are very memory inefficient. We might, however, cast them into categorical types if they have a reasonably low number of unique values. Let's check that:"},{"metadata":{"trusted":true},"cell_type":"code","source":"old_memory_usage = train_raw.memory_usage(deep = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ordinality_of_cats = train_raw.describe(include = [np.object]).T.sort_values('unique')\nordinality_of_cats","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's turn all of the columns with less than 300 unique values into categoricals."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_less_memory = train_raw.copy()\nlow_card_cols = ordinality_of_cats.query('unique < 300').index.tolist()\nfor col in low_card_cols:\n    train_less_memory[col] = train_raw[col].astype('category')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_less_memory.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_less_memory.memory_usage(deep = True)/old_memory_usage","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"The categorical columns now take less than 3% of their original memory! "},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}