1_Real_Data_Extraction_and_Synthetic_Enrichment.ipynb ADDED
@@ -0,0 +1,1104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# ESCP AI for Big Data Management - Final Group Project Notebook 1\n",
8
+ "## Real Data Extraction and Synthetic Enrichment\n",
9
+ "\n",
10
+ "**Project:** The Price Decider - AI-Enhanced Book Pricing Intelligence\\\n",
11
+ "**Group:** Pietro Buscaglione, Aleksei TVERITINOV, Emma LITSCHER, Louis-Marie LAILLIER, William DE MICHELE\\\n",
12
+ "**Hugging Face Space:** https://huggingface.co/spaces/cusco2212/codingworkshopp\\\n",
13
+ "\n",
14
+ "This notebook documents the real-data and synthetic-data pipeline used for the final project. It covers: \\n",
15
+ "1. Web scraping `books.toscrape.com` to create the base product catalog.\\\n",
16
+ "2. Synthetic enrichment with popularity scores, review sentiment, and 18 months of sales history.\\\n",
17
+ "3. Export of the core datasets used by the analysis notebook and the Hugging Face application.\n"
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "4ba6aba8"
24
+ },
25
+ "source": [
26
+ "# πŸ€– **Data Collection, Creation, Storage, and Processing**\n"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "metadata": {
32
+ "id": "jpASMyIQMaAq"
33
+ },
34
+ "source": [
35
+ "## **1.** πŸ“¦ Install required packages"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": 1,
41
+ "metadata": {
42
+ "colab": {
43
+ "base_uri": "https://localhost:8080/"
44
+ },
45
+ "id": "f48c8f8c",
46
+ "outputId": "13d0dd5e-82c6-489f-b1f0-e970186a4eb7"
47
+ },
48
+ "outputs": [
49
+ {
50
+ "output_type": "stream",
51
+ "name": "stdout",
52
+ "text": [
53
+ "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
54
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
55
+ "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
56
+ "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
57
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
58
+ "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
59
+ "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
60
+ "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
61
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
62
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
63
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
64
+ "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
65
+ "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
66
+ "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.61.1)\n",
67
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\n",
68
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
69
+ "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
70
+ "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
71
+ "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
72
+ "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
73
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
74
+ "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
75
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
76
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
77
+ ]
78
+ }
79
+ ],
80
+ "source": [
81
+ "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "markdown",
86
+ "metadata": {
87
+ "id": "lquNYCbfL9IM"
88
+ },
89
+ "source": [
90
+ "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "markdown",
95
+ "metadata": {
96
+ "id": "0IWuNpxxYDJF"
97
+ },
98
+ "source": [
99
+ "### *a. Initial setup*\n",
100
+ "Define the base url of the website you will scrape as well as how and what you will scrape"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": 2,
106
+ "metadata": {
107
+ "id": "91d52125"
108
+ },
109
+ "outputs": [],
110
+ "source": [
111
+ "import requests\n",
112
+ "from bs4 import BeautifulSoup\n",
113
+ "import pandas as pd\n",
114
+ "import time\n",
115
+ "\n",
116
+ "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
117
+ "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
118
+ "\n",
119
+ "titles, prices, ratings = [], [], []"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {
125
+ "id": "oCdTsin2Yfp3"
126
+ },
127
+ "source": [
128
+ "### *b. Fill titles, prices, and ratings from the web pages*"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": 3,
134
+ "metadata": {
135
+ "id": "xqO5Y3dnYhxt"
136
+ },
137
+ "outputs": [],
138
+ "source": [
139
+ "# Loop through all 50 pages\n",
140
+ "for page in range(1, 51):\n",
141
+ " url = base_url.format(page)\n",
142
+ " response = requests.get(url, headers=headers)\n",
143
+ " soup = BeautifulSoup(response.content, \"html.parser\")\n",
144
+ " books = soup.find_all(\"article\", class_=\"product_pod\")\n",
145
+ "\n",
146
+ " for book in books:\n",
147
+ " titles.append(book.h3.a[\"title\"])\n",
148
+ " prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
149
+ " ratings.append(book.p.get(\"class\")[1])\n",
150
+ "\n",
151
+ " time.sleep(0.5) # polite scraping delay"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "markdown",
156
+ "metadata": {
157
+ "id": "T0TOeRC4Yrnn"
158
+ },
159
+ "source": [
160
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": 4,
166
+ "metadata": {
167
+ "id": "l5FkkNhUYTHh"
168
+ },
169
+ "outputs": [],
170
+ "source": [
171
+ "# πŸ—‚οΈ Create DataFrame\n",
172
+ "df_books = pd.DataFrame({\n",
173
+ " \"title\": titles,\n",
174
+ " \"price\": prices,\n",
175
+ " \"rating\": ratings\n",
176
+ "})"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "markdown",
181
+ "metadata": {
182
+ "id": "duI5dv3CZYvF"
183
+ },
184
+ "source": [
185
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 5,
191
+ "metadata": {
192
+ "id": "lC1U_YHtZifh"
193
+ },
194
+ "outputs": [],
195
+ "source": [
196
+ "# πŸ’Ύ Save to CSV\n",
197
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
198
+ "\n",
199
+ "# πŸ’Ύ Or save to Excel\n",
200
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "markdown",
205
+ "metadata": {
206
+ "id": "qMjRKMBQZlJi"
207
+ },
208
+ "source": [
209
+ "### *e. βœ‹πŸ»πŸ›‘β›”οΈ View first fiew lines*"
210
+ ]
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "execution_count": 6,
215
+ "metadata": {
216
+ "colab": {
217
+ "base_uri": "https://localhost:8080/",
218
+ "height": 0
219
+ },
220
+ "id": "O_wIvTxYZqCK",
221
+ "outputId": "349b36b0-c008-4fd5-d4a4-dba38ae18337"
222
+ },
223
+ "outputs": [
224
+ {
225
+ "output_type": "execute_result",
226
+ "data": {
227
+ "text/plain": [
228
+ " title price rating\n",
229
+ "0 A Light in the Attic 51.77 Three\n",
230
+ "1 Tipping the Velvet 53.74 One\n",
231
+ "2 Soumission 50.10 One\n",
232
+ "3 Sharp Objects 47.82 Four\n",
233
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
234
+ ],
235
+ "text/html": [
236
+ "\n",
237
+ " <div id=\"df-04c87660-4415-45e9-ad3b-3fa19d9402c2\" class=\"colab-df-container\">\n",
238
+ " <div>\n",
239
+ "<style scoped>\n",
240
+ " .dataframe tbody tr th:only-of-type {\n",
241
+ " vertical-align: middle;\n",
242
+ " }\n",
243
+ "\n",
244
+ " .dataframe tbody tr th {\n",
245
+ " vertical-align: top;\n",
246
+ " }\n",
247
+ "\n",
248
+ " .dataframe thead th {\n",
249
+ " text-align: right;\n",
250
+ " }\n",
251
+ "</style>\n",
252
+ "<table border=\"1\" class=\"dataframe\">\n",
253
+ " <thead>\n",
254
+ " <tr style=\"text-align: right;\">\n",
255
+ " <th></th>\n",
256
+ " <th>title</th>\n",
257
+ " <th>price</th>\n",
258
+ " <th>rating</th>\n",
259
+ " </tr>\n",
260
+ " </thead>\n",
261
+ " <tbody>\n",
262
+ " <tr>\n",
263
+ " <th>0</th>\n",
264
+ " <td>A Light in the Attic</td>\n",
265
+ " <td>51.77</td>\n",
266
+ " <td>Three</td>\n",
267
+ " </tr>\n",
268
+ " <tr>\n",
269
+ " <th>1</th>\n",
270
+ " <td>Tipping the Velvet</td>\n",
271
+ " <td>53.74</td>\n",
272
+ " <td>One</td>\n",
273
+ " </tr>\n",
274
+ " <tr>\n",
275
+ " <th>2</th>\n",
276
+ " <td>Soumission</td>\n",
277
+ " <td>50.10</td>\n",
278
+ " <td>One</td>\n",
279
+ " </tr>\n",
280
+ " <tr>\n",
281
+ " <th>3</th>\n",
282
+ " <td>Sharp Objects</td>\n",
283
+ " <td>47.82</td>\n",
284
+ " <td>Four</td>\n",
285
+ " </tr>\n",
286
+ " <tr>\n",
287
+ " <th>4</th>\n",
288
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
289
+ " <td>54.23</td>\n",
290
+ " <td>Five</td>\n",
291
+ " </tr>\n",
292
+ " </tbody>\n",
293
+ "</table>\n",
294
+ "</div>\n",
295
+ " <div class=\"colab-df-buttons\">\n",
296
+ "\n",
297
+ " <div class=\"colab-df-container\">\n",
298
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-04c87660-4415-45e9-ad3b-3fa19d9402c2')\"\n",
299
+ " title=\"Convert this dataframe to an interactive table.\"\n",
300
+ " style=\"display:none;\">\n",
301
+ "\n",
302
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
303
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
304
+ " </svg>\n",
305
+ " </button>\n",
306
+ "\n",
307
+ " <style>\n",
308
+ " .colab-df-container {\n",
309
+ " display:flex;\n",
310
+ " gap: 12px;\n",
311
+ " }\n",
312
+ "\n",
313
+ " .colab-df-convert {\n",
314
+ " background-color: #E8F0FE;\n",
315
+ " border: none;\n",
316
+ " border-radius: 50%;\n",
317
+ " cursor: pointer;\n",
318
+ " display: none;\n",
319
+ " fill: #1967D2;\n",
320
+ " height: 32px;\n",
321
+ " padding: 0 0 0 0;\n",
322
+ " width: 32px;\n",
323
+ " }\n",
324
+ "\n",
325
+ " .colab-df-convert:hover {\n",
326
+ " background-color: #E2EBFA;\n",
327
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
328
+ " fill: #174EA6;\n",
329
+ " }\n",
330
+ "\n",
331
+ " .colab-df-buttons div {\n",
332
+ " margin-bottom: 4px;\n",
333
+ " }\n",
334
+ "\n",
335
+ " [theme=dark] .colab-df-convert {\n",
336
+ " background-color: #3B4455;\n",
337
+ " fill: #D2E3FC;\n",
338
+ " }\n",
339
+ "\n",
340
+ " [theme=dark] .colab-df-convert:hover {\n",
341
+ " background-color: #434B5C;\n",
342
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
343
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
344
+ " fill: #FFFFFF;\n",
345
+ " }\n",
346
+ " </style>\n",
347
+ "\n",
348
+ " <script>\n",
349
+ " const buttonEl =\n",
350
+ " document.querySelector('#df-04c87660-4415-45e9-ad3b-3fa19d9402c2 button.colab-df-convert');\n",
351
+ " buttonEl.style.display =\n",
352
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
353
+ "\n",
354
+ " async function convertToInteractive(key) {\n",
355
+ " const element = document.querySelector('#df-04c87660-4415-45e9-ad3b-3fa19d9402c2');\n",
356
+ " const dataTable =\n",
357
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
358
+ " [key], {});\n",
359
+ " if (!dataTable) return;\n",
360
+ "\n",
361
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
362
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
363
+ " + ' to learn more about interactive tables.';\n",
364
+ " element.innerHTML = '';\n",
365
+ " dataTable['output_type'] = 'display_data';\n",
366
+ " await google.colab.output.renderOutput(dataTable, element);\n",
367
+ " const docLink = document.createElement('div');\n",
368
+ " docLink.innerHTML = docLinkHtml;\n",
369
+ " element.appendChild(docLink);\n",
370
+ " }\n",
371
+ " </script>\n",
372
+ " </div>\n",
373
+ "\n",
374
+ "\n",
375
+ " </div>\n",
376
+ " </div>\n"
377
+ ],
378
+ "application/vnd.google.colaboratory.intrinsic+json": {
379
+ "type": "dataframe",
380
+ "variable_name": "df_books",
381
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
382
+ }
383
+ },
384
+ "metadata": {},
385
+ "execution_count": 6
386
+ }
387
+ ],
388
+ "source": [
389
+ "df_books.head()"
390
+ ]
391
+ },
392
+ {
393
+ "cell_type": "markdown",
394
+ "metadata": {
395
+ "id": "p-1Pr2szaqLk"
396
+ },
397
+ "source": [
398
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "markdown",
403
+ "metadata": {
404
+ "id": "SIaJUGIpaH4V"
405
+ },
406
+ "source": [
407
+ "### *a. Initial setup*"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": 7,
413
+ "metadata": {
414
+ "id": "-gPXGcRPuV_9"
415
+ },
416
+ "outputs": [],
417
+ "source": [
418
+ "import numpy as np\n",
419
+ "import random\n",
420
+ "from datetime import datetime\n",
421
+ "import warnings\n",
422
+ "\n",
423
+ "warnings.filterwarnings(\"ignore\")\n",
424
+ "random.seed(2025)\n",
425
+ "np.random.seed(2025)"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "markdown",
430
+ "metadata": {
431
+ "id": "pY4yCoIuaQqp"
432
+ },
433
+ "source": [
434
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "execution_count": 8,
440
+ "metadata": {
441
+ "id": "mnd5hdAbaNjz"
442
+ },
443
+ "outputs": [],
444
+ "source": [
445
+ "def generate_popularity_score(rating):\n",
446
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
447
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
448
+ " return int(np.clip(base + trend_factor, 1, 5))"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "markdown",
453
+ "metadata": {
454
+ "id": "n4-TaNTFgPak"
455
+ },
456
+ "source": [
457
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"popularity_score\" column from \"rating\"*"
458
+ ]
459
+ },
460
+ {
461
+ "cell_type": "code",
462
+ "execution_count": 9,
463
+ "metadata": {
464
+ "id": "V-G3OCUCgR07"
465
+ },
466
+ "outputs": [],
467
+ "source": [
468
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)"
469
+ ]
470
+ },
471
+ {
472
+ "cell_type": "markdown",
473
+ "metadata": {
474
+ "id": "HnngRNTgacYt"
475
+ },
476
+ "source": [
477
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": 10,
483
+ "metadata": {
484
+ "id": "kUtWmr8maZLZ"
485
+ },
486
+ "outputs": [],
487
+ "source": [
488
+ "def get_sentiment(popularity_score):\n",
489
+ " if popularity_score <= 2:\n",
490
+ " return \"negative\"\n",
491
+ " elif popularity_score == 3:\n",
492
+ " return \"neutral\"\n",
493
+ " else:\n",
494
+ " return \"positive\""
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "markdown",
499
+ "metadata": {
500
+ "id": "HF9F9HIzgT7Z"
501
+ },
502
+ "source": [
503
+ "### *e. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
504
+ ]
505
+ },
506
+ {
507
+ "cell_type": "code",
508
+ "execution_count": 11,
509
+ "metadata": {
510
+ "id": "tafQj8_7gYCG"
511
+ },
512
+ "outputs": [],
513
+ "source": [
514
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)"
515
+ ]
516
+ },
517
+ {
518
+ "cell_type": "markdown",
519
+ "metadata": {
520
+ "id": "T8AdKkmASq9a"
521
+ },
522
+ "source": [
523
+ "## **4.** πŸ“ˆ Generate synthetic book sales data of 18 months"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "markdown",
528
+ "metadata": {
529
+ "id": "OhXbdGD5fH0c"
530
+ },
531
+ "source": [
532
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
533
+ ]
534
+ },
535
+ {
536
+ "cell_type": "code",
537
+ "execution_count": 12,
538
+ "metadata": {
539
+ "id": "qkVhYPXGbgEn"
540
+ },
541
+ "outputs": [],
542
+ "source": [
543
+ "def generate_sales_profile(sentiment):\n",
544
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
545
+ "\n",
546
+ " if sentiment == \"positive\":\n",
547
+ " base = random.randint(200, 300)\n",
548
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
549
+ " elif sentiment == \"negative\":\n",
550
+ " base = random.randint(20, 80)\n",
551
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
552
+ " else: # neutral\n",
553
+ " base = random.randint(80, 160)\n",
554
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
555
+ "\n",
556
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
557
+ " noise = np.random.normal(0, 5, len(months))\n",
558
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
559
+ "\n",
560
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "markdown",
565
+ "metadata": {
566
+ "id": "L2ak1HlcgoTe"
567
+ },
568
+ "source": [
569
+ "### *b. Run the function as part of building sales_data*"
570
+ ]
571
+ },
572
+ {
573
+ "cell_type": "code",
574
+ "execution_count": 13,
575
+ "metadata": {
576
+ "id": "SlJ24AUafoDB"
577
+ },
578
+ "outputs": [],
579
+ "source": [
580
+ "sales_data = []\n",
581
+ "for _, row in df_books.iterrows():\n",
582
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
583
+ " for month, units in records:\n",
584
+ " sales_data.append({\n",
585
+ " \"title\": row[\"title\"],\n",
586
+ " \"month\": month,\n",
587
+ " \"units_sold\": units,\n",
588
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
589
+ " })"
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "markdown",
594
+ "metadata": {
595
+ "id": "4IXZKcCSgxnq"
596
+ },
597
+ "source": [
598
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a df_sales DataFrame from sales_data*"
599
+ ]
600
+ },
601
+ {
602
+ "cell_type": "code",
603
+ "execution_count": 14,
604
+ "metadata": {
605
+ "id": "wcN6gtiZg-ws"
606
+ },
607
+ "outputs": [],
608
+ "source": [
609
+ "df_sales = pd.DataFrame(sales_data)"
610
+ ]
611
+ },
612
+ {
613
+ "cell_type": "markdown",
614
+ "metadata": {
615
+ "id": "EhIjz9WohAmZ"
616
+ },
617
+ "source": [
618
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
619
+ ]
620
+ },
621
+ {
622
+ "cell_type": "code",
623
+ "execution_count": 15,
624
+ "metadata": {
625
+ "colab": {
626
+ "base_uri": "https://localhost:8080/"
627
+ },
628
+ "id": "MzbZvLcAhGaH",
629
+ "outputId": "c692bb04-7263-4115-a2ba-c72fe0180722"
630
+ },
631
+ "outputs": [
632
+ {
633
+ "output_type": "stream",
634
+ "name": "stdout",
635
+ "text": [
636
+ " title month units_sold sentiment_label\n",
637
+ "0 A Light in the Attic 2024-08 100 neutral\n",
638
+ "1 A Light in the Attic 2024-09 109 neutral\n",
639
+ "2 A Light in the Attic 2024-10 102 neutral\n",
640
+ "3 A Light in the Attic 2024-11 107 neutral\n",
641
+ "4 A Light in the Attic 2024-12 108 neutral\n"
642
+ ]
643
+ }
644
+ ],
645
+ "source": [
646
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
647
+ "\n",
648
+ "print(df_sales.head())"
649
+ ]
650
+ },
651
+ {
652
+ "cell_type": "markdown",
653
+ "metadata": {
654
+ "id": "7g9gqBgQMtJn"
655
+ },
656
+ "source": [
657
+ "## **5.** 🎯 Generate synthetic customer reviews"
658
+ ]
659
+ },
660
+ {
661
+ "cell_type": "markdown",
662
+ "metadata": {
663
+ "id": "Gi4y9M9KuDWx"
664
+ },
665
+ "source": [
666
+ "### *a. βœ‹πŸ»πŸ›‘β›”οΈ Ask ChatGPT to create a list of 50 distinct generic book review texts for the sentiment labels \"positive\", \"neutral\", and \"negative\" called synthetic_reviews_by_sentiment*"
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "execution_count": 16,
672
+ "metadata": {
673
+ "id": "b3cd2a50"
674
+ },
675
+ "outputs": [],
676
+ "source": [
677
+ "synthetic_reviews_by_sentiment = {\n",
678
+ " \"positive\": [\n",
679
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
680
+ " \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
681
+ " \"One of the best books I've read this year β€” inspiring and emotionally rich.\",\n",
682
+ " \"The author's storytelling was vivid and powerful. Highly recommended!\",\n",
683
+ " \"An absolute masterpiece. I couldn't put it down from start to finish.\",\n",
684
+ " \"Gripping, intelligent, and beautifully crafted β€” I loved every page.\",\n",
685
+ " \"The emotional depth and layered narrative were just perfect.\",\n",
686
+ " \"A thought-provoking journey with stunning character development.\",\n",
687
+ " \"Everything about this book just clicked. A top-tier read!\",\n",
688
+ " \"A flawless blend of emotion, intrigue, and style. Truly impressive.\",\n",
689
+ " \"Absolutely stunning work of fiction. Five stars from me.\",\n",
690
+ " \"Remarkably executed with breathtaking prose.\",\n",
691
+ " \"The pacing was perfect and I was hooked from page one.\",\n",
692
+ " \"Heartfelt and hopeful β€” a story well worth telling.\",\n",
693
+ " \"A vivid journey through complex emotions and stunning imagery.\",\n",
694
+ " \"This book had soul. Every word felt like it mattered.\",\n",
695
+ " \"It delivered more than I ever expected. Powerful and wise.\",\n",
696
+ " \"The characters leapt off the page and into my heart.\",\n",
697
+ " \"I could see every scene clearly in my mind β€” beautifully descriptive.\",\n",
698
+ " \"Refreshing, original, and impossible to forget.\",\n",
699
+ " \"A radiant celebration of resilience and love.\",\n",
700
+ " \"Powerful themes handled with grace and insight.\",\n",
701
+ " \"An unforgettable literary experience.\",\n",
702
+ " \"The best book club pick we’ve had all year.\",\n",
703
+ " \"A layered, lyrical narrative that resonates deeply.\",\n",
704
+ " \"Surprising, profound, and deeply humane.\",\n",
705
+ " \"One of those rare books I wish I could read again for the first time.\",\n",
706
+ " \"Both epic and intimate β€” a perfect balance.\",\n",
707
+ " \"It reads like a love letter to the human spirit.\",\n",
708
+ " \"Satisfying and uplifting with a memorable ending.\",\n",
709
+ " \"This novel deserves every bit of praise it gets.\",\n",
710
+ " \"Introspective, emotional, and elegantly composed.\",\n",
711
+ " \"A tour de force in contemporary fiction.\",\n",
712
+ " \"Left me smiling, teary-eyed, and completely fulfilled.\",\n",
713
+ " \"A novel with the rare ability to entertain and enlighten.\",\n",
714
+ " \"Incredibly moving. I highlighted so many lines.\",\n",
715
+ " \"A smart, sensitive take on relationships and identity.\",\n",
716
+ " \"You feel wiser by the end of it.\",\n",
717
+ " \"A gorgeously crafted tale about hope and second chances.\",\n",
718
+ " \"Poignant and real β€” a beautiful escape.\",\n",
719
+ " \"Brims with insight and authenticity.\",\n",
720
+ " \"Compelling characters and a satisfying plot.\",\n",
721
+ " \"An empowering and important read.\",\n",
722
+ " \"Elegantly crafted and deeply humane.\",\n",
723
+ " \"Taut storytelling that never lets go.\",\n",
724
+ " \"Each chapter offered a new treasure.\",\n",
725
+ " \"Lyrical writing that stays with you.\",\n",
726
+ " \"A wonderful blend of passion and thoughtfulness.\",\n",
727
+ " \"Uplifting, honest, and completely engrossing.\",\n",
728
+ " \"This one made me believe in storytelling again.\"\n",
729
+ " ],\n",
730
+ " \"neutral\": [\n",
731
+ " \"An average book β€” not great, but not bad either.\",\n",
732
+ " \"Some parts really stood out, others felt a bit flat.\",\n",
733
+ " \"It was okay overall. A decent way to pass the time.\",\n",
734
+ " \"The writing was fine, though I didn’t fully connect with the story.\",\n",
735
+ " \"Had a few memorable moments but lacked depth in some areas.\",\n",
736
+ " \"A mixed experience β€” neither fully engaging nor forgettable.\",\n",
737
+ " \"There was potential, but it didn't quite come together for me.\",\n",
738
+ " \"A reasonable effort that just didn’t leave a lasting impression.\",\n",
739
+ " \"Serviceable but not something I'd go out of my way to recommend.\",\n",
740
+ " \"Not much to dislike, but not much to rave about either.\",\n",
741
+ " \"It had its strengths, though they didn’t shine consistently.\",\n",
742
+ " \"I’m on the fence β€” parts were enjoyable, others not so much.\",\n",
743
+ " \"The book had a unique concept but lacked execution.\",\n",
744
+ " \"A middle-of-the-road read.\",\n",
745
+ " \"Engaging at times, but it lost momentum.\",\n",
746
+ " \"Would have benefited from stronger character development.\",\n",
747
+ " \"It passed the time, but I wouldn't reread it.\",\n",
748
+ " \"The plot had some holes that affected immersion.\",\n",
749
+ " \"Mediocre pacing made it hard to stay invested.\",\n",
750
+ " \"Satisfying in parts, underwhelming in others.\",\n",
751
+ " \"Neutral on this one β€” didn’t love it or hate it.\",\n",
752
+ " \"Fairly forgettable but with glimpses of promise.\",\n",
753
+ " \"The themes were solid, but not well explored.\",\n",
754
+ " \"Competent, just not compelling.\",\n",
755
+ " \"Had moments of clarity and moments of confusion.\",\n",
756
+ " \"I didn’t regret reading it, but I wouldn’t recommend it.\",\n",
757
+ " \"Readable, yet uninspired.\",\n",
758
+ " \"There was a spark, but it didn’t ignite.\",\n",
759
+ " \"A slow burn that didn’t quite catch fire.\",\n",
760
+ " \"I expected more nuance given the premise.\",\n",
761
+ " \"A safe, inoffensive choice.\",\n",
762
+ " \"Some parts lagged, others piqued my interest.\",\n",
763
+ " \"Decent, but needed polish.\",\n",
764
+ " \"Moderately engaging but didn’t stick the landing.\",\n",
765
+ " \"It simply lacked that emotional punch.\",\n",
766
+ " \"Just fine β€” no better, no worse.\",\n",
767
+ " \"Some thoughtful passages amid otherwise dry writing.\",\n",
768
+ " \"I appreciated the ideas more than the execution.\",\n",
769
+ " \"Struggled with cohesion.\",\n",
770
+ " \"Solidly average.\",\n",
771
+ " \"Good on paper, flat in practice.\",\n",
772
+ " \"A few bright spots, but mostly dim.\",\n",
773
+ " \"The kind of book that fades from memory.\",\n",
774
+ " \"It scratched the surface but didn’t dig deep.\",\n",
775
+ " \"Standard fare with some promise.\",\n",
776
+ " \"Okay, but not memorable.\",\n",
777
+ " \"Had potential that went unrealized.\",\n",
778
+ " \"Could have been tighter, sharper, deeper.\",\n",
779
+ " \"A blend of mediocrity and mild interest.\",\n",
780
+ " \"I kept reading, but barely.\"\n",
781
+ " ],\n",
782
+ " \"negative\": [\n",
783
+ " \"I struggled to get through this one β€” it just didn’t grab me.\",\n",
784
+ " \"The plot was confusing and the characters felt underdeveloped.\",\n",
785
+ " \"Disappointing. I had high hopes, but they weren't met.\",\n",
786
+ " \"Uninspired writing and a story that never quite took off.\",\n",
787
+ " \"Unfortunately, it was dull and predictable throughout.\",\n",
788
+ " \"The pacing dragged and I couldn’t find anything compelling.\",\n",
789
+ " \"This felt like a chore to read β€” lacked heart and originality.\",\n",
790
+ " \"Nothing really worked for me in this book.\",\n",
791
+ " \"A frustrating read that left me unsatisfied.\",\n",
792
+ " \"I kept hoping it would improve, but it never did.\",\n",
793
+ " \"The characters didn’t feel real, and the dialogue was forced.\",\n",
794
+ " \"I couldn't connect with the story at all.\",\n",
795
+ " \"A slow, meandering narrative with little payoff.\",\n",
796
+ " \"Tried too hard to be deep, but just felt empty.\",\n",
797
+ " \"The tone was uneven and confusing.\",\n",
798
+ " \"Way too repetitive and lacking progression.\",\n",
799
+ " \"The ending was abrupt and unsatisfying.\",\n",
800
+ " \"No emotional resonance β€” I felt nothing throughout.\",\n",
801
+ " \"I expected much more, but this fell flat.\",\n",
802
+ " \"Poorly edited and full of clichΓ©s.\",\n",
803
+ " \"The premise was interesting, but poorly executed.\",\n",
804
+ " \"Just didn’t live up to the praise.\",\n",
805
+ " \"A disjointed mess from start to finish.\",\n",
806
+ " \"Overly long and painfully dull.\",\n",
807
+ " \"Dialogue that felt robotic and unrealistic.\",\n",
808
+ " \"A hollow shell of what it could’ve been.\",\n",
809
+ " \"It lacked a coherent structure.\",\n",
810
+ " \"More confusing than complex.\",\n",
811
+ " \"Reading it felt like a task, not a treat.\",\n",
812
+ " \"There was no tension, no emotion β€” just words.\",\n",
813
+ " \"Characters with no motivation or development.\",\n",
814
+ " \"The plot twists were nonsensical.\",\n",
815
+ " \"Regret buying this book.\",\n",
816
+ " \"Nothing drew me in, nothing made me stay.\",\n",
817
+ " \"Too many subplots and none were satisfying.\",\n",
818
+ " \"Tedious and unimaginative.\",\n",
819
+ " \"Like reading a rough draft.\",\n",
820
+ " \"Disjointed, distant, and disappointing.\",\n",
821
+ " \"A lot of buildup with no payoff.\",\n",
822
+ " \"I don’t understand the hype.\",\n",
823
+ " \"This book simply didn’t work.\",\n",
824
+ " \"Forgettable in every sense.\",\n",
825
+ " \"More effort should’ve gone into editing.\",\n",
826
+ " \"The story lost its way early on.\",\n",
827
+ " \"It dragged endlessly.\",\n",
828
+ " \"I kept checking how many pages were left.\",\n",
829
+ " \"This lacked vision and clarity.\",\n",
830
+ " \"I expected substance β€” got fluff.\",\n",
831
+ " \"It failed to make me care.\"\n",
832
+ " ]\n",
833
+ "}"
834
+ ]
835
+ },
836
+ {
837
+ "cell_type": "markdown",
838
+ "metadata": {
839
+ "id": "fQhfVaDmuULT"
840
+ },
841
+ "source": [
842
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
843
+ ]
844
+ },
845
+ {
846
+ "cell_type": "code",
847
+ "execution_count": 17,
848
+ "metadata": {
849
+ "id": "l2SRc3PjuTGM"
850
+ },
851
+ "outputs": [],
852
+ "source": [
853
+ "review_rows = []\n",
854
+ "for _, row in df_books.iterrows():\n",
855
+ " title = row['title']\n",
856
+ " sentiment_label = row['sentiment_label']\n",
857
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
858
+ " sampled_reviews = random.sample(review_pool, 10)\n",
859
+ " for review_text in sampled_reviews:\n",
860
+ " review_rows.append({\n",
861
+ " \"title\": title,\n",
862
+ " \"sentiment_label\": sentiment_label,\n",
863
+ " \"review_text\": review_text,\n",
864
+ " \"rating\": row['rating'],\n",
865
+ " \"popularity_score\": row['popularity_score']\n",
866
+ " })"
867
+ ]
868
+ },
869
+ {
870
+ "cell_type": "markdown",
871
+ "metadata": {
872
+ "id": "bmJMXF-Bukdm"
873
+ },
874
+ "source": [
875
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
876
+ ]
877
+ },
878
+ {
879
+ "cell_type": "code",
880
+ "execution_count": 18,
881
+ "metadata": {
882
+ "id": "ZUKUqZsuumsp"
883
+ },
884
+ "outputs": [],
885
+ "source": [
886
+ "df_reviews = pd.DataFrame(review_rows)\n",
887
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
888
+ ]
889
+ },
890
+ {
891
+ "cell_type": "code",
892
+ "execution_count": 19,
893
+ "metadata": {
894
+ "colab": {
895
+ "base_uri": "https://localhost:8080/"
896
+ },
897
+ "id": "3946e521",
898
+ "outputId": "514d7bef-0488-4933-b03c-953b9e8a7f66"
899
+ },
900
+ "outputs": [
901
+ {
902
+ "output_type": "stream",
903
+ "name": "stdout",
904
+ "text": [
905
+ "βœ… Wrote synthetic_title_level_features.csv\n",
906
+ "βœ… Wrote synthetic_monthly_revenue_series.csv\n"
907
+ ]
908
+ }
909
+ ],
910
+ "source": [
911
+ "\n",
912
+ "# ============================================================\n",
913
+ "# βœ… Create \"R-ready\" derived inputs (root-level files)\n",
914
+ "# ============================================================\n",
915
+ "# These two files make the R notebook robust and fast:\n",
916
+ "# 1) synthetic_title_level_features.csv -> regression-ready, one row per title\n",
917
+ "# 2) synthetic_monthly_revenue_series.csv -> forecasting-ready, one row per month\n",
918
+ "\n",
919
+ "import numpy as np\n",
920
+ "\n",
921
+ "def _safe_num(s):\n",
922
+ " return pd.to_numeric(\n",
923
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
924
+ " errors=\"coerce\"\n",
925
+ " )\n",
926
+ "\n",
927
+ "# --- Clean book metadata (price/rating) ---\n",
928
+ "df_books_r = df_books.copy()\n",
929
+ "if \"price\" in df_books_r.columns:\n",
930
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
931
+ "if \"rating\" in df_books_r.columns:\n",
932
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
933
+ "\n",
934
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
935
+ "\n",
936
+ "# --- Clean sales ---\n",
937
+ "df_sales_r = df_sales.copy()\n",
938
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
939
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
940
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
941
+ "\n",
942
+ "# --- Clean reviews ---\n",
943
+ "df_reviews_r = df_reviews.copy()\n",
944
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
945
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
946
+ "if \"rating\" in df_reviews_r.columns:\n",
947
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
948
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
949
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
950
+ "\n",
951
+ "# --- Sentiment shares per title (from reviews) ---\n",
952
+ "sent_counts = (\n",
953
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
954
+ " .size()\n",
955
+ " .unstack(fill_value=0)\n",
956
+ ")\n",
957
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
958
+ " if lab not in sent_counts.columns:\n",
959
+ " sent_counts[lab] = 0\n",
960
+ "\n",
961
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
962
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
963
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
964
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
965
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
966
+ "sent_counts = sent_counts.reset_index()\n",
967
+ "\n",
968
+ "# --- Sales aggregation per title ---\n",
969
+ "sales_by_title = (\n",
970
+ " df_sales_r.dropna(subset=[\"title\"])\n",
971
+ " .groupby(\"title\", as_index=False)\n",
972
+ " .agg(\n",
973
+ " months_observed=(\"month\", \"nunique\"),\n",
974
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
975
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
976
+ " )\n",
977
+ ")\n",
978
+ "\n",
979
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
980
+ "df_title = (\n",
981
+ " sales_by_title\n",
982
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
983
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
984
+ " on=\"title\", how=\"left\")\n",
985
+ ")\n",
986
+ "\n",
987
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
988
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
989
+ "\n",
990
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
991
+ "print(\"βœ… Wrote synthetic_title_level_features.csv\")\n",
992
+ "\n",
993
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
994
+ "monthly_rev = (\n",
995
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
996
+ ")\n",
997
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
998
+ "\n",
999
+ "df_monthly = (\n",
1000
+ " monthly_rev.dropna(subset=[\"month\"])\n",
1001
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
1002
+ " .sum()\n",
1003
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
1004
+ " .sort_values(\"month\")\n",
1005
+ ")\n",
1006
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
1007
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
1008
+ " df_monthly = (\n",
1009
+ " df_sales_r.dropna(subset=[\"month\"])\n",
1010
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
1011
+ " .sum()\n",
1012
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
1013
+ " .sort_values(\"month\")\n",
1014
+ " )\n",
1015
+ "\n",
1016
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1017
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1018
+ "print(\"βœ… Wrote synthetic_monthly_revenue_series.csv\")\n"
1019
+ ]
1020
+ },
1021
+ {
1022
+ "cell_type": "markdown",
1023
+ "metadata": {
1024
+ "id": "RYvGyVfXuo54"
1025
+ },
1026
+ "source": [
1027
+ "### *d. βœ‹πŸ»πŸ›‘β›”οΈ View the first few lines*"
1028
+ ]
1029
+ },
1030
+ {
1031
+ "cell_type": "code",
1032
+ "execution_count": 20,
1033
+ "metadata": {
1034
+ "colab": {
1035
+ "base_uri": "https://localhost:8080/"
1036
+ },
1037
+ "id": "xfE8NMqOurKo",
1038
+ "outputId": "191730ba-d5e2-4df7-97d2-99feb0b704af"
1039
+ },
1040
+ "outputs": [
1041
+ {
1042
+ "output_type": "stream",
1043
+ "name": "stdout",
1044
+ "text": [
1045
+ " title sentiment_label \\\n",
1046
+ "0 A Light in the Attic neutral \n",
1047
+ "1 A Light in the Attic neutral \n",
1048
+ "2 A Light in the Attic neutral \n",
1049
+ "3 A Light in the Attic neutral \n",
1050
+ "4 A Light in the Attic neutral \n",
1051
+ "\n",
1052
+ " review_text rating popularity_score \n",
1053
+ "0 Had potential that went unrealized. Three 3 \n",
1054
+ "1 The themes were solid, but not well explored. Three 3 \n",
1055
+ "2 It simply lacked that emotional punch. Three 3 \n",
1056
+ "3 Serviceable but not something I'd go out of my... Three 3 \n",
1057
+ "4 Standard fare with some promise. Three 3 \n"
1058
+ ]
1059
+ }
1060
+ ],
1061
+ "source": [
1062
+ "print(df_reviews.head())"
1063
+ ]
1064
+ }
1065
+ ],
1066
+ "metadata": {
1067
+ "colab": {
1068
+ "collapsed_sections": [
1069
+ "jpASMyIQMaAq",
1070
+ "lquNYCbfL9IM",
1071
+ "0IWuNpxxYDJF",
1072
+ "oCdTsin2Yfp3",
1073
+ "T0TOeRC4Yrnn",
1074
+ "duI5dv3CZYvF",
1075
+ "qMjRKMBQZlJi",
1076
+ "p-1Pr2szaqLk",
1077
+ "SIaJUGIpaH4V",
1078
+ "pY4yCoIuaQqp",
1079
+ "n4-TaNTFgPak",
1080
+ "HnngRNTgacYt",
1081
+ "HF9F9HIzgT7Z",
1082
+ "T8AdKkmASq9a",
1083
+ "OhXbdGD5fH0c",
1084
+ "L2ak1HlcgoTe",
1085
+ "4IXZKcCSgxnq",
1086
+ "EhIjz9WohAmZ",
1087
+ "Gi4y9M9KuDWx",
1088
+ "fQhfVaDmuULT",
1089
+ "bmJMXF-Bukdm",
1090
+ "RYvGyVfXuo54"
1091
+ ],
1092
+ "provenance": []
1093
+ },
1094
+ "kernelspec": {
1095
+ "display_name": "Python 3",
1096
+ "name": "python3"
1097
+ },
1098
+ "language_info": {
1099
+ "name": "python"
1100
+ }
1101
+ },
1102
+ "nbformat": 4,
1103
+ "nbformat_minor": 0
1104
+ }
2_Data_Analysis_Quantitative_and_Qualitative.ipynb ADDED
The diff for this file is too large to render. See raw diff