{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom tqdm.notebook import tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:14:01.582034Z","iopub.execute_input":"2025-05-27T21:14:01.582267Z","iopub.status.idle":"2025-05-27T21:14:06.296220Z","shell.execute_reply.started":"2025-05-27T21:14:01.582247Z","shell.execute_reply":"2025-05-27T21:14:06.295066Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"articles = pd.read_csv(\"/kaggle/input/h-and-m-personalized-fashion-recommendations/articles.csv\")\ncustomers = pd.read_csv(\"/kaggle/input/h-and-m-personalized-fashion-recommendations/customers.csv\")\ntransactions = pd.read_csv(\"/kaggle/input/h-and-m-personalized-fashion-recommendations/transactions_train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:14:24.769106Z","iopub.execute_input":"2025-05-27T21:14:24.769421Z","iopub.status.idle":"2025-05-27T21:15:57.084828Z","shell.execute_reply.started":"2025-05-27T21:14:24.769395Z","shell.execute_reply":"2025-05-27T21:15:57.083939Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## ACTICLES","metadata":{}},{"cell_type":"code","source":"articles.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:16:21.805042Z","iopub.execute_input":"2025-05-27T21:16:21.806636Z","iopub.status.idle":"2025-05-27T21:16:21.885560Z","shell.execute_reply.started":"2025-05-27T21:16:21.806534Z","shell.execute_reply":"2025-05-27T21:16:21.884473Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"articles.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:17:00.695231Z","iopub.execute_input":"2025-05-27T21:17:00.695575Z","iopub.status.idle":"2025-05-27T21:17:00.818974Z","shell.execute_reply.started":"2025-05-27T21:17:00.695551Z","shell.execute_reply":"2025-05-27T21:17:00.817882Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"numeric_cols = articles.select_dtypes(include='int64')\nnegative_ones_count = (numeric_cols == -1).sum()\n\nprint(negative_ones_count)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:19:46.725282Z","iopub.execute_input":"2025-05-27T21:19:46.725633Z","iopub.status.idle":"2025-05-27T21:19:46.753285Z","shell.execute_reply.started":"2025-05-27T21:19:46.725610Z","shell.execute_reply":"2025-05-27T21:19:46.752007Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Có thể thấy dữ liệu không có giá trị Nan. Tuy nhiên lại chứa giá trị -1 nhưng phần trăm trên tổng data ít\n* Ngoài cột product_type_no những cột có giá trị -1 khác có thể không hữu dụng hoặc có thể dựa vào những trường khác\n* Chỉ làm sạch cột product_type_no\n* Có những giá trị cùng product_code nhưng khác product_name. Có thể là sai xót khi nhập liệu","metadata":{}},{"cell_type":"code","source":"# Làm sạch product_name\ndef clean_name(name):\n    name = str(name).lower().strip()  \n    name = name.replace('(1)', '')  \n    name = ' '.join(name.split())  \n    return name\n    \narticles['cleaned_name'] = articles['prod_name'].apply(clean_name)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:34:37.242877Z","iopub.execute_input":"2025-05-27T21:34:37.243203Z","iopub.status.idle":"2025-05-27T21:34:37.327450Z","shell.execute_reply.started":"2025-05-27T21:34:37.243178Z","shell.execute_reply":"2025-05-27T21:34:37.326474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"standard_names = articles.groupby('product_code')['cleaned_name'] \\\n                            .agg(lambda x: x.value_counts().idxmax()) \\\n                            .reset_index().rename(columns={'cleaned_name': 'standard_name'})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:34:44.348124Z","iopub.execute_input":"2025-05-27T21:34:44.348850Z","iopub.status.idle":"2025-05-27T21:34:54.668160Z","shell.execute_reply.started":"2025-05-27T21:34:44.348820Z","shell.execute_reply":"2025-05-27T21:34:54.667130Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"articles = articles.merge(standard_names, on='product_code', how='left')\narticles['prod_name'] = articles['standard_name']\n\narticles.drop(columns=['cleaned_name', 'standard_name'], inplace=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:35:01.044320Z","iopub.execute_input":"2025-05-27T21:35:01.045039Z","iopub.status.idle":"2025-05-27T21:35:01.168468Z","shell.execute_reply.started":"2025-05-27T21:35:01.045009Z","shell.execute_reply":"2025-05-27T21:35:01.167479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Fill giá trị -1 của trường product_type_no dựa trên trường product_no,prod_name\nvalid_reference = articles[\n    (articles['product_type_no'] != -1) &\n    (articles['product_type_name'].str.lower() != 'unknown') &\n    (articles['product_group_name'].str.lower() != 'unknown')\n].drop_duplicates(subset=['product_code'])\n\n# Chỉ giữ các cột cần thiết\nvalid_reference = valid_reference[['product_code', 'product_type_no', 'product_type_name', 'product_group_name']]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:35:17.152749Z","iopub.execute_input":"2025-05-27T21:35:17.153035Z","iopub.status.idle":"2025-05-27T21:35:17.261821Z","shell.execute_reply.started":"2025-05-27T21:35:17.153015Z","shell.execute_reply":"2025-05-27T21:35:17.260965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gộp dữ liệu gốc với dữ liệu hợp lệ theo product_code\narticles = articles.merge(valid_reference, on='product_code', how='left', suffixes=('', '_ref'))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:35:24.451966Z","iopub.execute_input":"2025-05-27T21:35:24.452277Z","iopub.status.idle":"2025-05-27T21:35:24.536224Z","shell.execute_reply.started":"2025-05-27T21:35:24.452253Z","shell.execute_reply":"2025-05-27T21:35:24.535203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Với product_type_no\narticles['product_type_no'] = articles.apply(\n    lambda row: row['product_type_no_ref'] if row['product_type_no'] == -1 else row['product_type_no'],\n    axis=1\n)\n\n# Với product_type_name\narticles['product_type_name'] = articles.apply(\n    lambda row: row['product_type_name_ref'] if row['product_type_name'].lower() == 'unknown' else row['product_type_name'],\n    axis=1\n)\n\n# Với product_group_name\narticles['product_group_name'] = articles.apply(\n    lambda row: row['product_group_name_ref'] if row['product_group_name'].lower() == 'unknown' else row['product_group_name'],\n    axis=1\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:35:45.267251Z","iopub.execute_input":"2025-05-27T21:35:45.267574Z","iopub.status.idle":"2025-05-27T21:35:47.618023Z","shell.execute_reply.started":"2025-05-27T21:35:45.267548Z","shell.execute_reply":"2025-05-27T21:35:47.617112Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Xóa cột tham chiếu\narticles.drop(columns=['product_type_no_ref', 'product_type_name_ref', 'product_group_name_ref'], inplace=True)\n\n# Và chuyển product_type_no về kiểu int\narticles['product_type_no'] = articles['product_type_no'].astype('Int64')  # hoặc int nếu chắc chắn không có NaN\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:36:00.948554Z","iopub.execute_input":"2025-05-27T21:36:00.949011Z","iopub.status.idle":"2025-05-27T21:36:00.993675Z","shell.execute_reply.started":"2025-05-27T21:36:00.948964Z","shell.execute_reply":"2025-05-27T21:36:00.992496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"articles.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:36:12.645280Z","iopub.execute_input":"2025-05-27T21:36:12.646015Z","iopub.status.idle":"2025-05-27T21:36:12.665361Z","shell.execute_reply.started":"2025-05-27T21:36:12.645984Z","shell.execute_reply":"2025-05-27T21:36:12.664522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"type_counts = articles['product_type_name'].value_counts()\ntype_counts","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:36:40.453891Z","iopub.execute_input":"2025-05-27T21:36:40.454230Z","iopub.status.idle":"2025-05-27T21:36:40.471024Z","shell.execute_reply.started":"2025-05-27T21:36:40.454207Z","shell.execute_reply":"2025-05-27T21:36:40.469970Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### ACTICLES VISUALIZATION","metadata":{}},{"cell_type":"markdown","source":"****Q1: LOẠI SẢN PHẨM NÀO ĐƯỢC SẢN XUẤT NHIỀU NHẤT****","metadata":{}},{"cell_type":"code","source":"type_percent = (type_counts / type_counts.sum() * 100).round(2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:37:01.556922Z","iopub.execute_input":"2025-05-27T21:37:01.557240Z","iopub.status.idle":"2025-05-27T21:37:01.563084Z","shell.execute_reply.started":"2025-05-27T21:37:01.557217Z","shell.execute_reply":"2025-05-27T21:37:01.561896Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"top10 = type_percent.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:37:18.954287Z","iopub.execute_input":"2025-05-27T21:37:18.954654Z","iopub.status.idle":"2025-05-27T21:37:18.959974Z","shell.execute_reply.started":"2025-05-27T21:37:18.954617Z","shell.execute_reply":"2025-05-27T21:37:18.959079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.cm as cm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:40:08.175413Z","iopub.execute_input":"2025-05-27T21:40:08.175755Z","iopub.status.idle":"2025-05-27T21:40:08.180931Z","shell.execute_reply.started":"2025-05-27T21:40:08.175731Z","shell.execute_reply":"2025-05-27T21:40:08.179758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels = top10.index[::-1]\nvalues = top10.values[::-1]\nnorm = plt.Normalize(values.min(), values.max())\ncolors = cm.magma(norm(values)) \n# Vẽ biểu đồ\nplt.figure(figsize=(8, 5))\nbars = plt.barh(top10.index[::-1], top10.values[::-1], color=colors)\n\n# Thêm giá trị phần trăm lên đầu cột\nfor i, v in enumerate(top10.values[::-1]):\n    plt.text(v + 0.2, i, f'{v:.2f}%', va='center')\n\nplt.xlabel('% Quantity')\nplt.title('% Quantity by Product Type')\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:40:10.279163Z","iopub.execute_input":"2025-05-27T21:40:10.279556Z","iopub.status.idle":"2025-05-27T21:40:10.555536Z","shell.execute_reply.started":"2025-05-27T21:40:10.279530Z","shell.execute_reply":"2025-05-27T21:40:10.554443Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Q2:NHỮNG MẶT HÀNG NÀO CÓ GIÁ TRỊ CAO NHẤT**","metadata":{}},{"cell_type":"code","source":"# Giả sử df_t là transactions có article_id, price\n# df_a là articles có article_id, prod_name\n\n# Kết hợp bảng để có tên sản phẩm\nmerged = transactions.merge(articles[['article_id', 'prod_name']], on='article_id', how='left')\n\n# Tìm giá cao nhất cho mỗi article_id\nmax_price = merged.groupby(['article_id', 'prod_name'])['price'].max().reset_index()\n\n# Lấy top 10 sản phẩm theo giá\ntop10_price = max_price.sort_values(by='price', ascending=False).head(10)\n\nprint(top10_price)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:51:19.927582Z","iopub.execute_input":"2025-05-27T21:51:19.927986Z","iopub.status.idle":"2025-05-27T21:51:35.309399Z","shell.execute_reply.started":"2025-05-27T21:51:19.927961Z","shell.execute_reply":"2025-05-27T21:51:35.308298Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"articles.groupby(['index_group_name', 'index_name']).count()['article_id']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:45:17.447920Z","iopub.execute_input":"2025-05-27T21:45:17.448271Z","iopub.status.idle":"2025-05-27T21:45:17.547065Z","shell.execute_reply.started":"2025-05-27T21:45:17.448248Z","shell.execute_reply":"2025-05-27T21:45:17.546293Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Ladiswear chiếm một phần đáng kể. Sport chiếm một phần ít","metadata":{}},{"cell_type":"markdown","source":"## CUSTOMERS","metadata":{}},{"cell_type":"code","source":"customers.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:56:24.436871Z","iopub.execute_input":"2025-05-27T21:56:24.437207Z","iopub.status.idle":"2025-05-27T21:56:24.459700Z","shell.execute_reply.started":"2025-05-27T21:56:24.437188Z","shell.execute_reply":"2025-05-27T21:56:24.458668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"customers.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T21:56:44.837359Z","iopub.execute_input":"2025-05-27T21:56:44.837703Z","iopub.status.idle":"2025-05-27T21:56:46.023516Z","shell.execute_reply.started":"2025-05-27T21:56:44.837678Z","shell.execute_reply":"2025-05-27T21:56:46.022797Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Một lượng lớn giá trị NaN trong trường FN, Active. Tuy nhiên không hữu dụng khi phân tích nên không thay đổi\n* Hơn 1,1% giá trị tuổi bị thiếu không quá ảnh hưởng\n* Nhìn chung data sạch ","metadata":{}},{"cell_type":"markdown","source":"### CUSTOMERS VISUALIZATION","metadata":{}},{"cell_type":"markdown","source":"**Q1: Khách hàng chủ yếu thuộc độ tuổi nào ?**","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nfrom matplotlib import pyplot as plt\nsns.set_style(\"darkgrid\")\nf, ax = plt.subplots(figsize=(10,5))\nax = sns.histplot(data=customers, x='age', bins=50, color='orange')\nax.set_xlabel('Distribution of the customers age')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:00:45.848539Z","iopub.execute_input":"2025-05-27T22:00:45.848929Z","iopub.status.idle":"2025-05-27T22:00:46.772305Z","shell.execute_reply.started":"2025-05-27T22:00:45.848903Z","shell.execute_reply":"2025-05-27T22:00:46.771285Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Q2: Nhóm tuổi nào có lượng đơn hàng nhiều nhất? Nhóm có nhiều đơn hàng nhất có đem lại nhiều doanh thu nhất cho công ty hay không ?**","metadata":{}},{"cell_type":"code","source":"# Tính tổng tiền chi tiêu của mỗi khách hàng.\ndf_cust_prices = transactions[[\"customer_id\", \"price\"]].groupby(\"customer_id\").sum()\ndf_cust_prices.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:09.427947Z","iopub.execute_input":"2025-05-27T22:07:09.428666Z","iopub.status.idle":"2025-05-27T22:07:23.895495Z","shell.execute_reply.started":"2025-05-27T22:07:09.428636Z","shell.execute_reply":"2025-05-27T22:07:23.894541Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Tính số lượng món hàng đã mua của mỗi khách hàng\ndf_cust_qty = transactions[[\"customer_id\", \"article_id\"]].groupby(\"customer_id\").count()\ndf_cust_qty.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:27.483833Z","iopub.execute_input":"2025-05-27T22:07:27.484122Z","iopub.status.idle":"2025-05-27T22:07:39.880863Z","shell.execute_reply.started":"2025-05-27T22:07:27.484104Z","shell.execute_reply":"2025-05-27T22:07:39.879920Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Kết hợp tổng tiền chi tiêu và số lượng sản phẩm mua thành một bảng.\ncust_qty_price = pd.merge(df_cust_prices, df_cust_qty, on='customer_id', how='inner')\ncust_qty_price.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:46.562892Z","iopub.execute_input":"2025-05-27T22:07:46.563209Z","iopub.status.idle":"2025-05-27T22:07:47.184771Z","shell.execute_reply.started":"2025-05-27T22:07:46.563186Z","shell.execute_reply":"2025-05-27T22:07:47.183764Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Ghép thêm thông tin chi tiết về khách hàng vào bảng đã tổng hợp.\ncust_details = pd.merge(cust_qty_price, customers, on='customer_id', how='inner')\ncust_details.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:51.156402Z","iopub.execute_input":"2025-05-27T22:07:51.156742Z","iopub.status.idle":"2025-05-27T22:07:52.471513Z","shell.execute_reply.started":"2025-05-27T22:07:51.156720Z","shell.execute_reply":"2025-05-27T22:07:52.470614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gán nhóm tuổi cho từng khách hàng để phân tích dễ hơn.\ncust_details['age_groups'] = pd.cut(cust_details['age'], bins=[16, 20, 30, 40,50, 60, 70, float('Inf')], labels=['16-20', '20-30','30-40','40-50','50-60','60-70' , '70+'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:56.290056Z","iopub.execute_input":"2025-05-27T22:07:56.290760Z","iopub.status.idle":"2025-05-27T22:07:56.352504Z","shell.execute_reply.started":"2025-05-27T22:07:56.290731Z","shell.execute_reply":"2025-05-27T22:07:56.351326Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8,5))\nplt.title(\"Purchased quantity by age group\\n\", fontweight=\"bold\", size=28)\ng = sns.barplot(x=\"age_groups\", y=\"Purchased Quantity(%)\", data=cust_details.groupby(\"age_groups\")[\"article_id\"].sum() \\\n            .transform(lambda x: (x / x.sum() * 100)).rename('Purchased Quantity(%)').reset_index(), palette=\"icefire\", edgecolor=\"black\")\nplt.xlabel(\"Age Group\",fontweight=\"bold\", size=22)\nplt.ylabel(\"Purchased Quantity (%)\",fontweight=\"bold\", size=19)\nfor container in g.containers:\n    g.bar_label(container, padding = 5, fmt='%.1f', fontsize=18, color=\"black\")\nplt.grid(axis=\"y\",color = 'grey', linestyle = '--', linewidth = 1.5)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:07:58.912448Z","iopub.execute_input":"2025-05-27T22:07:58.912793Z","iopub.status.idle":"2025-05-27T22:07:59.241112Z","shell.execute_reply.started":"2025-05-27T22:07:58.912768Z","shell.execute_reply":"2025-05-27T22:07:59.240057Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Nhóm tuổi 20-30 là nhóm có lượng mua hàng nhiều nhất","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(8,5))\nplt.title(\"Company Earnings by age group\\n\", fontweight=\"bold\", size=28)\ng = sns.barplot(x=\"age_groups\", y=\"earning(%)\", data=cust_details.groupby(\"age_groups\")[\"price\"].sum() \\\n            .transform(lambda x: (x / x.sum() * 100)).rename('earning(%)').reset_index(), palette=\"icefire\",edgecolor=\"black\")\nplt.xlabel(\"Age Group\",fontweight=\"bold\", size=22)\nplt.ylabel(\"Earnings (%)\",fontweight=\"bold\", size=25)\nfor container in g.containers:\n    g.bar_label(container, padding = 5, fmt='%.1f', fontsize=18, color=\"black\")\nplt.grid(axis=\"y\",color = 'grey', linestyle = '--', linewidth = 1.5)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:09:22.931397Z","iopub.execute_input":"2025-05-27T22:09:22.932213Z","iopub.status.idle":"2025-05-27T22:09:23.219331Z","shell.execute_reply.started":"2025-05-27T22:09:22.932181Z","shell.execute_reply":"2025-05-27T22:09:23.218310Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* *Nhóm 20-30 cũng là nhóm đem lại doanh thu nhiều nhất cho công ty*","metadata":{}},{"cell_type":"markdown","source":"**Q3: Số lượng đơn hàng có chênh lệch đối với khách hàng hay nhận tin và không hay nhận tin hay không?**","metadata":{}},{"cell_type":"code","source":"df_qty_by_age_news = (\n    cust_details\n    .groupby(['age_groups', 'fashion_news_frequency'])['article_id']\n    .count()\n    .reset_index()\n    .rename(columns={'article_id': 'purchased_qty'})\n)\ndf_qty_by_age_news = df_qty_by_age_news[df_qty_by_age_news['fashion_news_frequency'].isin(['Regularly', 'NONE'])]\ndf_qty_by_age_news['pct'] = df_qty_by_age_news.groupby('age_groups')['purchased_qty'].transform(lambda x: (x / x.sum()) * 100)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:12:38.829333Z","iopub.execute_input":"2025-05-27T22:12:38.829699Z","iopub.status.idle":"2025-05-27T22:12:39.001119Z","shell.execute_reply.started":"2025-05-27T22:12:38.829673Z","shell.execute_reply":"2025-05-27T22:12:39.000190Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(14, 7))\ng = sns.barplot(\n    data=df_qty_by_age_news,\n    x='age_groups',\n    y='pct',\n    hue='fashion_news_frequency',\n    palette={'Regularly': '#C68EFD', 'NONE': '#0118D8'}\n)\n\nplt.title(\"Purchased Quantity (%) by Fashion News Frequency & Age Group\", fontsize=20, fontweight='bold')\nplt.xlabel(\"Age Group\", fontsize=16, fontweight='bold')\nplt.ylabel(\"Purchased Quantity (%)\", fontsize=16, fontweight='bold')\nplt.legend(title='Fashion News Frequency', fontsize=12, title_fontsize=13)\nplt.grid(axis='y', linestyle='--', alpha=0.7)\n\n# ✅ Thêm số % trên từng cột\nfor container in g.containers:\n    g.bar_label(container, fmt='%.1f%%', fontsize=12, padding=3, color='black')\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:22:08.287325Z","iopub.execute_input":"2025-05-27T22:22:08.287650Z","iopub.status.idle":"2025-05-27T22:22:08.670006Z","shell.execute_reply.started":"2025-05-27T22:22:08.287628Z","shell.execute_reply":"2025-05-27T22:22:08.669143Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Có thể thấy lượng đơn hàng đến chủ yếu từ khách hàng không đăng kí nhận tin từ nhãn hàng\n* Có thể họ có xu hướng mua vì nhu cầu, sở thích chứ không chỉ vì những chương trình giảm giá,...","metadata":{}},{"cell_type":"markdown","source":"## TRANSACTIONS","metadata":{}},{"cell_type":"code","source":"transactions['t_dat'] = pd.to_datetime(transactions['t_dat'])\ntransactions['day_of_week'] = transactions['t_dat'].dt.weekday + 1\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:25:16.232123Z","iopub.execute_input":"2025-05-27T22:25:16.232848Z","iopub.status.idle":"2025-05-27T22:25:18.215906Z","shell.execute_reply.started":"2025-05-27T22:25:16.232817Z","shell.execute_reply":"2025-05-27T22:25:18.214886Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Đếm số lượt mua hàng theo từng ngày trong tuần\nday_counts = transactions['day_of_week'].value_counts().sort_index()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:26:03.000090Z","iopub.execute_input":"2025-05-27T22:26:03.000402Z","iopub.status.idle":"2025-05-27T22:26:03.189872Z","shell.execute_reply.started":"2025-05-27T22:26:03.000380Z","shell.execute_reply":"2025-05-27T22:26:03.188938Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8, 5))\nbars = plt.bar(day_counts.index, day_counts.values, color='dodgerblue')\n\n# Thêm nhãn\nplt.xticks(ticks=range(1, 8), labels=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])\nplt.xlabel('Day of Week')\nplt.ylabel('Number of Purchases')\nplt.title('Customer Purchase Frequency by Day of Week')\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-27T22:26:05.984433Z","iopub.execute_input":"2025-05-27T22:26:05.984797Z","iopub.status.idle":"2025-05-27T22:26:06.257421Z","shell.execute_reply.started":"2025-05-27T22:26:05.984766Z","shell.execute_reply":"2025-05-27T22:26:06.256540Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Lượng khách hàng tăng trong khoảng giữa tuần cho đến cuối tuần và giảm mạnh vào Chủ Nhật. Điều này có thể đến từ việc một số đất nước cuối tuần họ sẽ đóng cửa các cửa hàng và đơn hàng sẽ chỉ đến từ online","metadata":{}}]}