{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":31254,"databundleVersionId":3103714,"sourceType":"competition"}],"dockerImageVersionId":30170,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns # nice visualisations\nimport matplotlib.pyplot as plt # basic visualisation library\nimport datetime as dt # library to opearate on dates\n\nprint(\"pandas version: {}\".format(pd.__version__))\nprint(\"numpy version: {}\".format(np.__version__))\nprint(\"seaborn version: {}\".format(sns.__version__))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-05-22T13:14:25.227069Z","iopub.execute_input":"2024-05-22T13:14:25.227683Z","iopub.status.idle":"2024-05-22T13:14:26.589057Z","shell.execute_reply.started":"2024-05-22T13:14:25.227641Z","shell.execute_reply":"2024-05-22T13:14:26.587919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_articles = pd.read_csv(\"../input/h-and-m-personalized-fashion-recommendations/articles.csv\")\ndf_customers = pd.read_csv(\"../input/h-and-m-personalized-fashion-recommendations/customers.csv\")\ndf_transactions_train = pd.read_csv(\"../input/h-and-m-personalized-fashion-recommendations/transactions_train.csv\")","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-05-22T13:14:26.590773Z","iopub.execute_input":"2024-05-22T13:14:26.591149Z","iopub.status.idle":"2024-05-22T13:15:51.284101Z","shell.execute_reply.started":"2024-05-22T13:14:26.591112Z","shell.execute_reply":"2024-05-22T13:15:51.282404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"raw","source":"df_customers","metadata":{}},{"cell_type":"code","source":"df_customers","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:15:51.285833Z","iopub.execute_input":"2024-05-22T13:15:51.286209Z","iopub.status.idle":"2024-05-22T13:15:51.332133Z","shell.execute_reply.started":"2024-05-22T13:15:51.286162Z","shell.execute_reply":"2024-05-22T13:15:51.330742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_customers.describe()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:15:51.334559Z","iopub.execute_input":"2024-05-22T13:15:51.334885Z","iopub.status.idle":"2024-05-22T13:15:51.576418Z","shell.execute_reply.started":"2024-05-22T13:15:51.334835Z","shell.execute_reply":"2024-05-22T13:15:51.574676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_transactions_train['t_dat'] = pd.to_datetime(df_transactions_train['t_dat'])\nlatest_date = df_transactions_train['t_dat'].max()\nthree_months_ago = latest_date - pd.DateOffset(months=3)\nnew_df_transactions_train = df_transactions_train[df_transactions_train['t_dat'] >= three_months_ago]","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-05-22T13:15:51.577521Z","iopub.execute_input":"2024-05-22T13:15:51.577827Z","iopub.status.idle":"2024-05-22T13:15:59.791572Z","shell.execute_reply.started":"2024-05-22T13:15:51.577790Z","shell.execute_reply":"2024-05-22T13:15:59.790384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_data = pd.merge(new_df_transactions_train, df_articles, on='article_id', how='left')\nmerged_data = pd.merge(merged_data, df_customers, on='customer_id', how='left')","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:15:59.793995Z","iopub.execute_input":"2024-05-22T13:15:59.794263Z","iopub.status.idle":"2024-05-22T13:16:23.963804Z","shell.execute_reply.started":"2024-05-22T13:15:59.794230Z","shell.execute_reply":"2024-05-22T13:16:23.962056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"merged_data = merged_data.dropna(subset=['detail_desc'])\ncategorical_cols_missing = ['club_member_status', 'fashion_news_frequency']\nfor col in categorical_cols_missing:\n    merged_data[col].fillna(merged_data[col].mode()[0], inplace=True)\n\nnumerical_cols_missing = ['age']\nfor col in numerical_cols_missing:\n    merged_data[col].fillna(merged_data[col].median(), inplace=True)\nmerged_data['FN'] = merged_data['FN'].fillna(0)\nmerged_data['Active'] = merged_data['Active'].fillna(0)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:16:23.965544Z","iopub.execute_input":"2024-05-22T13:16:23.966040Z","iopub.status.idle":"2024-05-22T13:16:32.122278Z","shell.execute_reply.started":"2024-05-22T13:16:23.965985Z","shell.execute_reply":"2024-05-22T13:16:32.121407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"df_filtered = merged_data[(merged_data['age'] >= 18) & (merged_data['age'] <= 35)]","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:16:32.123666Z","iopub.execute_input":"2024-05-22T13:16:32.124300Z","iopub.status.idle":"2024-05-22T13:16:33.121804Z","shell.execute_reply.started":"2024-05-22T13:16:32.124257Z","shell.execute_reply":"2024-05-22T13:16:33.120782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_filtered.describe()","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:16:33.124882Z","iopub.execute_input":"2024-05-22T13:16:33.125251Z","iopub.status.idle":"2024-05-22T13:16:34.403226Z","shell.execute_reply.started":"2024-05-22T13:16:33.125205Z","shell.execute_reply":"2024-05-22T13:16:34.402351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_filtered","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:16:34.406231Z","iopub.execute_input":"2024-05-22T13:16:34.406541Z","iopub.status.idle":"2024-05-22T13:16:36.903192Z","shell.execute_reply.started":"2024-05-22T13:16:34.406503Z","shell.execute_reply":"2024-05-22T13:16:36.902290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n# !pip install ipywidgets\nfrom ipywidgets import interact, widgets","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:17:49.901085Z","iopub.execute_input":"2024-05-22T13:17:49.901506Z","iopub.status.idle":"2024-05-22T13:17:49.906019Z","shell.execute_reply.started":"2024-05-22T13:17:49.901448Z","shell.execute_reply":"2024-05-22T13:17:49.904913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"So below widgets shows for each club member status what is the different age groups present between 18-40","metadata":{}},{"cell_type":"code","source":"def plot_age_distribution(club_status):\n    subset = df_filtered.loc[df_filtered[\"club_member_status\"] == club_status]\n    age_groups = pd.cut(subset[\"age\"], bins=[18, 25, 30, 35, 40])\n    age_groups.value_counts().plot(kind=\"bar\", color=[\"skyblue\", \"lightgreen\"])\n\n# Club membership status options\nclub_status_options = df_filtered[\"club_member_status\"].unique()\n\n# Interactive dropdown for club membership status\ninteract(plot_age_distribution, club_status=club_status_options)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:17:53.975891Z","iopub.execute_input":"2024-05-22T13:17:53.976240Z","iopub.status.idle":"2024-05-22T13:17:56.187220Z","shell.execute_reply.started":"2024-05-22T13:17:53.976205Z","shell.execute_reply":"2024-05-22T13:17:56.186048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_age_distribution_product_group_name(product_group):\n    subset = df_filtered.loc[df_filtered[\"product_group_name\"] == product_group]\n    age_groups = pd.cut(subset[\"age\"], bins=[18, 25, 30, 35, 40])\n    age_groups.value_counts().plot(kind=\"bar\", color=[\"skyblue\", \"lightgreen\"])\n\n# Club membership status options\nproduct_group_options = df_filtered[\"product_group_name\"].unique()\n\n# Interactive dropdown for club membership status\ninteract(plot_age_distribution_product_group_name, product_group=product_group_options)","metadata":{"execution":{"iopub.status.busy":"2024-05-22T13:19:51.806567Z","iopub.execute_input":"2024-05-22T13:19:51.808221Z","iopub.status.idle":"2024-05-22T13:19:54.167759Z","shell.execute_reply.started":"2024-05-22T13:19:51.808097Z","shell.execute_reply":"2024-05-22T13:19:54.163003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tkinter as tk\nimport folium\nfrom tkinter import ttk\nfrom folium import GeoJson\n\n# Define constants for the canvas size\nCANVAS_WIDTH = 800\nCANVAS_HEIGHT = 600\n\nclass PurchasePatternMap:\n    def __init__(self, root):\n        self.root = root\n        self.root.title(\"H&M Purchase Patterns\")\n\n        # Load your H&M data into a pandas DataFrame (replace 'df' with your actual DataFrame)\n        df=df_filtered\n\n        # Calculate average price per age group\n        self.avg_price_age = df.groupby('age')['price'].mean().to_dictionary()\n\n        # Calculate price percentiles by club member status\n        self.price_percentiles_club_status = {}\n        for club_status in df['club_member_status'].unique():\n            club_data = df[df['club_member_status'] == club_status]\n            percentiles = club_data['price'].quantile([0.25, 0.5, 0.75])\n            self.price_percentiles_club_status[club_status] = percentiles.to_dictionary()\n\n        # Create a Canvas widget\n        self.canvas = tk.Canvas(root, width=CANVAS_WIDTH, height=CANVAS_HEIGHT, bg=\"white\")\n        self.canvas.pack()\n\n        # Create a Frame for the map\n        self.map_frame = ttk.Frame(root)\n        self.map_frame.place(x=0, y=0, width=CANVAS_WIDTH, height=CANVAS_HEIGHT)\n\n        # Create a map using Folium centered on London (replace with a relevant location)\n        self.m = folium.Map(location=[51.505, -0.09], zoom_start=13)\n        self.marker_group = folium.FeatureGroup(name=\"Purchase Patterns\")  # FeatureGroup for markers\n\n        # Define a function to determine color based on price range\n        def get_price_color(price, club_status):\n            percentiles = self.price_percentiles_club_status[club_status]\n            if price < percentiles[0.25]:\n                return \"green\"  # Low price range\n            elif price > percentiles[0.75]:\n                return \"red\"  # High price range\n            else:\n                return \"orange\"  # Medium price range\n\n        # Sample GeoJson data (replace with actual GeoJson data)\n        geojson_data = {\"type\": \"FeatureCollection\", \"features\": []}\n\n        # Add a GeoJson layer (replace with actual GeoJson data representing relevant regions)\n        folium.GeoJson(geojson=geojson_data, \n                       style_function=lambda feature: {\"fillColor\": get_price_color(self.avg_price_age[feature[\"properties\"][\"age_group\"]], feature[\"properties\"][\"club_member_status\"])}).add_to(self.marker_group)\n\n        self.m.add_child(self.marker_group)\n        self.m.save('map.html')\n\n        # Load the map into the tkinter application\n        self.load_map()\n        \n\n    def load_map(self):\n        # Use webbrowser to display the map HTML in a tkinter canvas\n        import webbrowser\n        webbrowser.open('map.html')\n\n# Run the application\nroot = tk.Tk()\napp = PurchasePatternMap(root)\nroot.mainloop()","metadata":{"execution":{"iopub.status.busy":"2024-05-21T13:59:19.128476Z","iopub.execute_input":"2024-05-21T13:59:19.129583Z","iopub.status.idle":"2024-05-21T13:59:19.518239Z","shell.execute_reply.started":"2024-05-21T13:59:19.129526Z","shell.execute_reply":"2024-05-21T13:59:19.516933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}