{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### How to read a large csv file with pandas","metadata":{}},{"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":"2022-07-07T15:04:20.358371Z","iopub.execute_input":"2022-07-07T15:04:20.358838Z","iopub.status.idle":"2022-07-07T15:04:20.388433Z","shell.execute_reply.started":"2022-07-07T15:04:20.358737Z","shell.execute_reply":"2022-07-07T15:04:20.387186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n#### references:\n\n1. read file by chunksize\n - https://stackoverflow.com/questions/25962114/how-do-i-read-a-large-csv-file-with-pandas\n - https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html\n1. convert 64bit numeric values to 32bit values: convert int64 to int32; convert float64 to float32\n - https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.select_dtypes.html\n - **warning**: if the values is out of 32bit value range, the conversion will be erroneous\n1. save data to parquet file: use compression='GZIP' to further decrease file size\n - https://arrow.apache.org/docs/python/parquet.html\n - https://arrow.apache.org/docs/python/generated/pyarrow.parquet.write_table.html?highlight=write_table\n\n#### steps:\n\n1. read csv by chunk. can set chunk size as 2 millon (i.e. chunksize = 20e5)\n1. convert int64 to int32 and float64 to float32 >> this will cut the file size to half\n1. save each chunk to a parquet file\n","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport gc\nimport copy\nimport os\nimport sys\n\nfrom pathlib import Path\nfrom datetime import datetime, date, time, timedelta\nfrom dateutil import relativedelta\n\nimport pyarrow.parquet as pq\nimport pyarrow as pa","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:04:29.055276Z","iopub.execute_input":"2022-07-07T15:04:29.055654Z","iopub.status.idle":"2022-07-07T15:04:29.060758Z","shell.execute_reply.started":"2022-07-07T15:04:29.055621Z","shell.execute_reply":"2022-07-07T15:04:29.059749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n#https://stackoverflow.com/questions/25962114/how-do-i-read-a-large-csv-file-with-pandas\nchunksize = 20e5\nprint('chunksize=', chunksize)\n\ndef process_big_csv(chunk, dest_file):\n    #---convert float64 to float32--------\n    float64_cols = chunk.select_dtypes(include=['float64']).columns.tolist()\n    chunk[float64_cols] = np.float32(chunk[float64_cols].values)\n    #---convert int64 to int32\n    int64_cols = chunk.select_dtypes(include=['int64']).columns.tolist()\n    chunk[int64_cols] = np.int32(chunk[int64_cols].values)\n    \n    #-- save to parquet file\n    table = pa.Table.from_pandas(chunk)\n    pq.write_table(table, dest_file, compression = 'GZIP')\n    \n    del table, chunk\n    gc.collect()\n\ntrain_file = '/kaggle/input/amex-default-prediction/train_data.csv'\nwith pd.read_csv(train_file, chunksize=chunksize) as reader:\n    for i, chunk in enumerate(reader):\n        dest_file = f'{i+1}.parquet'\n        process_big_csv(chunk, dest_file)","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:04:38.515360Z","iopub.execute_input":"2022-07-07T15:04:38.515691Z","iopub.status.idle":"2022-07-07T15:19:44.642266Z","shell.execute_reply.started":"2022-07-07T15:04:38.515665Z","shell.execute_reply":"2022-07-07T15:19:44.641086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## check output file","metadata":{}},{"cell_type":"code","source":"%%time\ntrain = pd.read_parquet('1.parquet')","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:20:39.678345Z","iopub.execute_input":"2022-07-07T15:20:39.678728Z","iopub.status.idle":"2022-07-07T15:20:49.661104Z","shell.execute_reply.started":"2022-07-07T15:20:39.678697Z","shell.execute_reply":"2022-07-07T15:20:49.660323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:20:51.165602Z","iopub.execute_input":"2022-07-07T15:20:51.166520Z","iopub.status.idle":"2022-07-07T15:20:51.173864Z","shell.execute_reply.started":"2022-07-07T15:20:51.166483Z","shell.execute_reply":"2022-07-07T15:20:51.172993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:20:52.660881Z","iopub.execute_input":"2022-07-07T15:20:52.661504Z","iopub.status.idle":"2022-07-07T15:20:52.694876Z","shell.execute_reply.started":"2022-07-07T15:20:52.661465Z","shell.execute_reply":"2022-07-07T15:20:52.694145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## display files and names","metadata":{}},{"cell_type":"code","source":"files = next(os.walk('.'))[2]\nparquet_files = []\nfor file in files:\n    if '.parquet' in file:\n        parquet_files.append(file)\n\nlen(parquet_files), parquet_files[:2]","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:21:03.363723Z","iopub.execute_input":"2022-07-07T15:21:03.364103Z","iopub.status.idle":"2022-07-07T15:21:03.372210Z","shell.execute_reply.started":"2022-07-07T15:21:03.364070Z","shell.execute_reply":"2022-07-07T15:21:03.371052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -lh","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:21:04.665710Z","iopub.execute_input":"2022-07-07T15:21:04.666656Z","iopub.status.idle":"2022-07-07T15:21:05.611063Z","shell.execute_reply.started":"2022-07-07T15:21:04.666614Z","shell.execute_reply":"2022-07-07T15:21:05.609864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}