{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"cell_type":"code","source":"# General imports\nimport numpy as np\nimport pandas as pd\nimport os, warnings, math\n\nfrom sklearn.preprocessing import LabelEncoder\n\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"########################### Helpers\n#################################################################################\n## -------------------\n## Memory Reducer\n# :df pandas dataframe to reduce size             # type: pd.DataFrame()\n# :verbose                                        # type: bool\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() / 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    end_mem = df.memory_usage().sum() / 1024**2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n    return df\n## -------------------","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### DATA LOAD\n#################################################################################\nprint('Load Data')\ntrain_df = pd.read_csv('../input/ashrae-energy-prediction/train.csv')\ntest_df = pd.read_csv('../input/ashrae-energy-prediction/test.csv')\n\nbuilding_df = pd.read_csv('../input/ashrae-energy-prediction/building_metadata.csv')\n\ntrain_weather_df = pd.read_csv('../input/ashrae-energy-prediction/weather_train.csv')\ntest_weather_df = pd.read_csv('../input/ashrae-energy-prediction/weather_test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Data Check\n#################################################################################\nprint('Main data:', list(train_df), train_df.info())\nprint('#'*20)\n\nprint('Buildings data:',list(building_df), building_df.info())\nprint('#'*20)\n\nprint('Weather data:',list(train_weather_df), train_weather_df.info())\nprint('#'*20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Convert timestamp to date\n#################################################################################\nfor df in [train_df, test_df, train_weather_df, test_weather_df]:\n    df['timestamp'] = pd.to_datetime(df['timestamp'])\n    \nfor df in [train_df, test_df]:\n    df['DT_M'] = df['timestamp'].dt.month.astype(np.int8)\n    df['DT_W'] = df['timestamp'].dt.weekofyear.astype(np.int8)\n    df['DT_D'] = df['timestamp'].dt.dayofyear.astype(np.int16)\n    \n    df['DT_hour'] = df['timestamp'].dt.hour.astype(np.int8)\n    df['DT_day_week'] = df['timestamp'].dt.dayofweek.astype(np.int8)\n    df['DT_day_month'] = df['timestamp'].dt.day.astype(np.int8)\n    df['DT_week_month'] = df['timestamp'].dt.day/7\n    df['DT_week_month'] = df['DT_week_month'].apply(lambda x: math.ceil(x)).astype(np.int8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Strings to category\n#################################################################################\nbuilding_df['primary_use'] = building_df['primary_use'].astype('category')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Building Transform\n#################################################################################\nbuilding_df['floor_count'] = building_df['floor_count'].fillna(0).astype(np.int8)\nbuilding_df['year_built'] = building_df['year_built'].fillna(-999).astype(np.int16)\n\nle = LabelEncoder()\nbuilding_df['primary_use'] = building_df['primary_use'].astype(str)\nbuilding_df['primary_use'] = le.fit_transform(building_df['primary_use']).astype(np.int8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Base check\n#################################################################################\ndo_not_convert = ['category','datetime64[ns]','object']\nfor df in [train_df, test_df, building_df, train_weather_df, test_weather_df]:\n    original = df.copy()\n    df = reduce_mem_usage(df)\n\n    for col in list(df):\n        if df[col].dtype.name not in do_not_convert:\n            if (df[col]-original[col]).sum()!=0:\n                df[col] = original[col]\n                print('Bad transformation', col)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Data Check\n#################################################################################\nprint('Main data:', list(train_df), train_df.info())\nprint('#'*20)\n\nprint('Buildings data:',list(building_df), building_df.info())\nprint('#'*20)\n\nprint('Weather data:',list(train_weather_df), train_weather_df.info())\nprint('#'*20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Export (using same names as in competition dataset)\n#################################################################################\ntrain_df.to_pickle('train.pkl')\ntest_df.to_pickle('test.pkl')\n\nbuilding_df.to_pickle('building_metadata.pkl')\n\ntrain_weather_df.to_pickle('weather_train.pkl')\ntest_weather_df.to_pickle('weather_test.pkl')","execution_count":null,"outputs":[]}],"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.6.6"}},"nbformat":4,"nbformat_minor":1}