teliii commited on
Commit
8abdc86
Β·
verified Β·
1 Parent(s): 3f522a9

Upload 2 files

Browse files
1_Data_Creation_(2).ipynb ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "4ba6aba8"
7
+ },
8
+ "source": [
9
+ "# πŸ€– **Data Collection, Creation, Storage, and Processing**\n"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {
15
+ "id": "jpASMyIQMaAq"
16
+ },
17
+ "source": [
18
+ "## **1.** πŸ“¦ Install required packages"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "metadata": {
25
+ "colab": {
26
+ "base_uri": "https://localhost:8080/"
27
+ },
28
+ "id": "f48c8f8c",
29
+ "outputId": "a0890314-02af-4935-e466-e090329e6564"
30
+ },
31
+ "outputs": [
32
+ {
33
+ "output_type": "stream",
34
+ "name": "stdout",
35
+ "text": [
36
+ "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
37
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
38
+ "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
39
+ "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
40
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
41
+ "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
42
+ "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
43
+ "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
44
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
45
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
46
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
47
+ "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
48
+ "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
49
+ "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.61.1)\n",
50
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\n",
51
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
52
+ "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
53
+ "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
54
+ "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
55
+ "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
56
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
57
+ "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
58
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
59
+ "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"
60
+ ]
61
+ }
62
+ ],
63
+ "source": [
64
+ "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "metadata": {
70
+ "id": "lquNYCbfL9IM"
71
+ },
72
+ "source": [
73
+ "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {
79
+ "id": "0IWuNpxxYDJF"
80
+ },
81
+ "source": [
82
+ "### *a. Initial setup*\n",
83
+ "Define the base url of the website you will scrape as well as how and what you will scrape"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": null,
89
+ "metadata": {
90
+ "id": "91d52125"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "import requests\n",
95
+ "from bs4 import BeautifulSoup\n",
96
+ "import pandas as pd\n",
97
+ "import time\n",
98
+ "\n",
99
+ "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
100
+ "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
101
+ "\n",
102
+ "titles, prices, ratings = [], [], []"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {
108
+ "id": "oCdTsin2Yfp3"
109
+ },
110
+ "source": [
111
+ "### *b. Fill titles, prices, and ratings from the web pages*"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": null,
117
+ "metadata": {
118
+ "id": "xqO5Y3dnYhxt"
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "# Loop through all 50 pages\n",
123
+ "for page in range(1, 51):\n",
124
+ " url = base_url.format(page)\n",
125
+ " response = requests.get(url, headers=headers)\n",
126
+ " soup = BeautifulSoup(response.content, \"html.parser\")\n",
127
+ " books = soup.find_all(\"article\", class_=\"product_pod\")\n",
128
+ "\n",
129
+ " for book in books:\n",
130
+ " titles.append(book.h3.a[\"title\"])\n",
131
+ " prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
132
+ " ratings.append(book.p.get(\"class\")[1])\n",
133
+ "\n",
134
+ " time.sleep(0.5) # polite scraping delay"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {
140
+ "id": "T0TOeRC4Yrnn"
141
+ },
142
+ "source": [
143
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": null,
149
+ "metadata": {
150
+ "id": "l5FkkNhUYTHh"
151
+ },
152
+ "outputs": [],
153
+ "source": [
154
+ "df_books = pd.DataFrame({\n",
155
+ " \"title\": titles,\n",
156
+ " \"price\": prices,\n",
157
+ " \"rating\": ratings\n",
158
+ "})"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "metadata": {
164
+ "id": "duI5dv3CZYvF"
165
+ },
166
+ "source": [
167
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "metadata": {
174
+ "id": "lC1U_YHtZifh"
175
+ },
176
+ "outputs": [],
177
+ "source": [
178
+ "# πŸ’Ύ Save to CSV\n",
179
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
180
+ "\n",
181
+ "# πŸ’Ύ Or save to Excel\n",
182
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "markdown",
187
+ "metadata": {
188
+ "id": "qMjRKMBQZlJi"
189
+ },
190
+ "source": [
191
+ "### *e. βœ‹πŸ»πŸ›‘β›”οΈ View first fiew lines*"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "metadata": {
198
+ "colab": {
199
+ "base_uri": "https://localhost:8080/"
200
+ },
201
+ "id": "O_wIvTxYZqCK",
202
+ "outputId": "316b08b8-3fa6-4207-bd83-9407cee43cc9"
203
+ },
204
+ "outputs": [
205
+ {
206
+ "output_type": "stream",
207
+ "name": "stdout",
208
+ "text": [
209
+ " title price rating\n",
210
+ "0 A Light in the Attic 51.77 Three\n",
211
+ "1 Tipping the Velvet 53.74 One\n",
212
+ "2 Soumission 50.10 One\n",
213
+ "3 Sharp Objects 47.82 Four\n",
214
+ "4 Sapiens: A Brief History of Humankind 54.23 Five\n"
215
+ ]
216
+ }
217
+ ],
218
+ "source": [
219
+ "print(df_books.head())"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "metadata": {
225
+ "id": "p-1Pr2szaqLk"
226
+ },
227
+ "source": [
228
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "markdown",
233
+ "metadata": {
234
+ "id": "SIaJUGIpaH4V"
235
+ },
236
+ "source": [
237
+ "### *a. Initial setup*"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "execution_count": null,
243
+ "metadata": {
244
+ "id": "-gPXGcRPuV_9"
245
+ },
246
+ "outputs": [],
247
+ "source": [
248
+ "import numpy as np\n",
249
+ "import random\n",
250
+ "from datetime import datetime\n",
251
+ "import warnings\n",
252
+ "\n",
253
+ "warnings.filterwarnings(\"ignore\")\n",
254
+ "random.seed(2025)\n",
255
+ "np.random.seed(2025)"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "metadata": {
261
+ "id": "pY4yCoIuaQqp"
262
+ },
263
+ "source": [
264
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
265
+ ]
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "execution_count": null,
270
+ "metadata": {
271
+ "id": "mnd5hdAbaNjz"
272
+ },
273
+ "outputs": [],
274
+ "source": [
275
+ "def generate_popularity_score(rating):\n",
276
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
277
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
278
+ " return int(np.clip(base + trend_factor, 1, 5))"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "markdown",
283
+ "metadata": {
284
+ "id": "n4-TaNTFgPak"
285
+ },
286
+ "source": [
287
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"popularity_score\" column from \"rating\"*"
288
+ ]
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": null,
293
+ "metadata": {
294
+ "id": "V-G3OCUCgR07"
295
+ },
296
+ "outputs": [],
297
+ "source": [
298
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)"
299
+ ]
300
+ },
301
+ {
302
+ "cell_type": "markdown",
303
+ "metadata": {
304
+ "id": "HnngRNTgacYt"
305
+ },
306
+ "source": [
307
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": null,
313
+ "metadata": {
314
+ "id": "kUtWmr8maZLZ"
315
+ },
316
+ "outputs": [],
317
+ "source": [
318
+ "def get_sentiment(popularity_score):\n",
319
+ " if popularity_score <= 2:\n",
320
+ " return \"negative\"\n",
321
+ " elif popularity_score == 3:\n",
322
+ " return \"neutral\"\n",
323
+ " else:\n",
324
+ " return \"positive\""
325
+ ]
326
+ },
327
+ {
328
+ "cell_type": "markdown",
329
+ "metadata": {
330
+ "id": "HF9F9HIzgT7Z"
331
+ },
332
+ "source": [
333
+ "### *e. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "execution_count": null,
339
+ "metadata": {
340
+ "id": "tafQj8_7gYCG"
341
+ },
342
+ "outputs": [],
343
+ "source": [
344
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "markdown",
349
+ "metadata": {
350
+ "id": "T8AdKkmASq9a"
351
+ },
352
+ "source": [
353
+ "## **4.** πŸ“ˆ Generate synthetic book sales data of 18 months"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "markdown",
358
+ "metadata": {
359
+ "id": "OhXbdGD5fH0c"
360
+ },
361
+ "source": [
362
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
363
+ ]
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "execution_count": null,
368
+ "metadata": {
369
+ "id": "qkVhYPXGbgEn"
370
+ },
371
+ "outputs": [],
372
+ "source": [
373
+ "def generate_sales_profile(sentiment):\n",
374
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
375
+ "\n",
376
+ " if sentiment == \"positive\":\n",
377
+ " base = random.randint(200, 300)\n",
378
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
379
+ " elif sentiment == \"negative\":\n",
380
+ " base = random.randint(20, 80)\n",
381
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
382
+ " else: # neutral\n",
383
+ " base = random.randint(80, 160)\n",
384
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
385
+ "\n",
386
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
387
+ " noise = np.random.normal(0, 5, len(months))\n",
388
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
389
+ "\n",
390
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
391
+ ]
392
+ },
393
+ {
394
+ "cell_type": "markdown",
395
+ "metadata": {
396
+ "id": "L2ak1HlcgoTe"
397
+ },
398
+ "source": [
399
+ "### *b. Run the function as part of building sales_data*"
400
+ ]
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "execution_count": null,
405
+ "metadata": {
406
+ "id": "SlJ24AUafoDB"
407
+ },
408
+ "outputs": [],
409
+ "source": [
410
+ "sales_data = []\n",
411
+ "for _, row in df_books.iterrows():\n",
412
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
413
+ " for month, units in records:\n",
414
+ " sales_data.append({\n",
415
+ " \"title\": row[\"title\"],\n",
416
+ " \"month\": month,\n",
417
+ " \"units_sold\": units,\n",
418
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
419
+ " })"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "metadata": {
425
+ "id": "4IXZKcCSgxnq"
426
+ },
427
+ "source": [
428
+ "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a df_sales DataFrame from sales_data*"
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "code",
433
+ "execution_count": null,
434
+ "metadata": {
435
+ "id": "wcN6gtiZg-ws"
436
+ },
437
+ "outputs": [],
438
+ "source": [
439
+ "df_sales = pd.DataFrame(sales_data)"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "markdown",
444
+ "metadata": {
445
+ "id": "EhIjz9WohAmZ"
446
+ },
447
+ "source": [
448
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "code",
453
+ "execution_count": null,
454
+ "metadata": {
455
+ "colab": {
456
+ "base_uri": "https://localhost:8080/"
457
+ },
458
+ "id": "MzbZvLcAhGaH",
459
+ "outputId": "59a87098-00cd-4d47-ecc7-931728a764e9"
460
+ },
461
+ "outputs": [
462
+ {
463
+ "output_type": "stream",
464
+ "name": "stdout",
465
+ "text": [
466
+ " title month units_sold sentiment_label\n",
467
+ "0 A Light in the Attic 2024-08 285 positive\n",
468
+ "1 A Light in the Attic 2024-09 296 positive\n",
469
+ "2 A Light in the Attic 2024-10 291 positive\n",
470
+ "3 A Light in the Attic 2024-11 297 positive\n",
471
+ "4 A Light in the Attic 2024-12 300 positive\n"
472
+ ]
473
+ }
474
+ ],
475
+ "source": [
476
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
477
+ "\n",
478
+ "print(df_sales.head())"
479
+ ]
480
+ },
481
+ {
482
+ "cell_type": "markdown",
483
+ "metadata": {
484
+ "id": "7g9gqBgQMtJn"
485
+ },
486
+ "source": [
487
+ "## **5.** 🎯 Generate synthetic customer reviews"
488
+ ]
489
+ },
490
+ {
491
+ "cell_type": "markdown",
492
+ "metadata": {
493
+ "id": "Gi4y9M9KuDWx"
494
+ },
495
+ "source": [
496
+ "### *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*"
497
+ ]
498
+ },
499
+ {
500
+ "cell_type": "code",
501
+ "execution_count": null,
502
+ "metadata": {
503
+ "id": "b3cd2a50"
504
+ },
505
+ "outputs": [],
506
+ "source": [
507
+ "synthetic_reviews_by_sentiment = {\n",
508
+ " \"positive\": [\n",
509
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
510
+ " \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
511
+ " \"One of the best books I've read this year β€” inspiring and emotionally rich.\",\n",
512
+ " ],\n",
513
+ " \"neutral\": [\n",
514
+ " \"An average book β€” not great, but not bad either.\",\n",
515
+ " \"Some parts really stood out, others felt a bit flat.\",\n",
516
+ " \"It was okay overall. A decent way to pass the time.\",\n",
517
+ " ],\n",
518
+ " \"negative\": [\n",
519
+ " \"I struggled to get through this one β€” it just didn’t grab me.\",\n",
520
+ " \"The plot was confusing and the characters felt underdeveloped.\",\n",
521
+ " \"Disappointing. I had high hopes, but they weren't met.\",\n",
522
+ " ]\n",
523
+ "}"
524
+ ]
525
+ },
526
+ {
527
+ "cell_type": "markdown",
528
+ "metadata": {
529
+ "id": "fQhfVaDmuULT"
530
+ },
531
+ "source": [
532
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
533
+ ]
534
+ },
535
+ {
536
+ "cell_type": "code",
537
+ "execution_count": null,
538
+ "metadata": {
539
+ "id": "l2SRc3PjuTGM"
540
+ },
541
+ "outputs": [],
542
+ "source": [
543
+ "review_rows = []\n",
544
+ "for _, row in df_books.iterrows():\n",
545
+ " title = row['title']\n",
546
+ " sentiment_label = row['sentiment_label']\n",
547
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
548
+ " # Using random.choices to allow sampling with replacement, as the review_pool is smaller than k=10\n",
549
+ " sampled_reviews = random.choices(review_pool, k=10)\n",
550
+ " for review_text in sampled_reviews:\n",
551
+ " review_rows.append({\n",
552
+ " \"title\": title,\n",
553
+ " \"sentiment_label\": sentiment_label,\n",
554
+ " \"review_text\": review_text,\n",
555
+ " \"rating\": row['rating'],\n",
556
+ " \"popularity_score\": row['popularity_score']\n",
557
+ " })"
558
+ ]
559
+ },
560
+ {
561
+ "cell_type": "markdown",
562
+ "metadata": {
563
+ "id": "bmJMXF-Bukdm"
564
+ },
565
+ "source": [
566
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
567
+ ]
568
+ },
569
+ {
570
+ "cell_type": "code",
571
+ "execution_count": null,
572
+ "metadata": {
573
+ "id": "ZUKUqZsuumsp"
574
+ },
575
+ "outputs": [],
576
+ "source": [
577
+ "df_reviews = pd.DataFrame(review_rows)\n",
578
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
579
+ ]
580
+ },
581
+ {
582
+ "cell_type": "markdown",
583
+ "source": [
584
+ "### *c. inputs for R*"
585
+ ],
586
+ "metadata": {
587
+ "id": "_602pYUS3gY5"
588
+ }
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": null,
593
+ "metadata": {
594
+ "colab": {
595
+ "base_uri": "https://localhost:8080/"
596
+ },
597
+ "id": "3946e521",
598
+ "outputId": "619ccfd5-a469-4f05-f623-ec4a08b11070"
599
+ },
600
+ "outputs": [
601
+ {
602
+ "output_type": "stream",
603
+ "name": "stdout",
604
+ "text": [
605
+ "βœ… Wrote synthetic_title_level_features.csv\n",
606
+ "βœ… Wrote synthetic_monthly_revenue_series.csv\n"
607
+ ]
608
+ }
609
+ ],
610
+ "source": [
611
+ "import numpy as np\n",
612
+ "\n",
613
+ "def _safe_num(s):\n",
614
+ " return pd.to_numeric(\n",
615
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
616
+ " errors=\"coerce\"\n",
617
+ " )\n",
618
+ "\n",
619
+ "# --- Clean book metadata (price/rating) ---\n",
620
+ "df_books_r = df_books.copy()\n",
621
+ "if \"price\" in df_books_r.columns:\n",
622
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
623
+ "if \"rating\" in df_books_r.columns:\n",
624
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
625
+ "\n",
626
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
627
+ "\n",
628
+ "# --- Clean sales ---\n",
629
+ "df_sales_r = df_sales.copy()\n",
630
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
631
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
632
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
633
+ "\n",
634
+ "# --- Clean reviews ---\n",
635
+ "df_reviews_r = df_reviews.copy()\n",
636
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
637
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
638
+ "if \"rating\" in df_reviews_r.columns:\n",
639
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
640
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
641
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
642
+ "\n",
643
+ "# --- Sentiment shares per title (from reviews) ---\n",
644
+ "sent_counts = (\n",
645
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
646
+ " .size()\n",
647
+ " .unstack(fill_value=0)\n",
648
+ ")\n",
649
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
650
+ " if lab not in sent_counts.columns:\n",
651
+ " sent_counts[lab] = 0\n",
652
+ "\n",
653
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
654
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
655
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
656
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
657
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
658
+ "sent_counts = sent_counts.reset_index()\n",
659
+ "\n",
660
+ "# --- Sales aggregation per title ---\n",
661
+ "sales_by_title = (\n",
662
+ " df_sales_r.dropna(subset=[\"title\"])\n",
663
+ " .groupby(\"title\", as_index=False)\n",
664
+ " .agg(\n",
665
+ " months_observed=(\"month\", \"nunique\"),\n",
666
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
667
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
668
+ " )\n",
669
+ ")\n",
670
+ "\n",
671
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
672
+ "df_title = (\n",
673
+ " sales_by_title\n",
674
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
675
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
676
+ " on=\"title\", how=\"left\")\n",
677
+ ")\n",
678
+ "\n",
679
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
680
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
681
+ "\n",
682
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
683
+ "print(\"βœ… Wrote synthetic_title_level_features.csv\")\n",
684
+ "\n",
685
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
686
+ "monthly_rev = (\n",
687
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
688
+ ")\n",
689
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
690
+ "\n",
691
+ "df_monthly = (\n",
692
+ " monthly_rev.dropna(subset=[\"month\"])\n",
693
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
694
+ " .sum()\n",
695
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
696
+ " .sort_values(\"month\")\n",
697
+ ")\n",
698
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
699
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
700
+ " df_monthly = (\n",
701
+ " df_sales_r.dropna(subset=[\"month\"])\n",
702
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
703
+ " .sum()\n",
704
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
705
+ " .sort_values(\"month\")\n",
706
+ " )\n",
707
+ "\n",
708
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
709
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
710
+ "print(\"βœ… Wrote synthetic_monthly_revenue_series.csv\")\n"
711
+ ]
712
+ },
713
+ {
714
+ "cell_type": "markdown",
715
+ "metadata": {
716
+ "id": "RYvGyVfXuo54"
717
+ },
718
+ "source": [
719
+ "### *d. βœ‹πŸ»πŸ›‘β›”οΈ View the first few lines*"
720
+ ]
721
+ },
722
+ {
723
+ "cell_type": "code",
724
+ "execution_count": 39,
725
+ "metadata": {
726
+ "colab": {
727
+ "base_uri": "https://localhost:8080/"
728
+ },
729
+ "id": "xfE8NMqOurKo",
730
+ "outputId": "1e2bb4d3-a14e-481f-8f97-bd61afac10e6"
731
+ },
732
+ "outputs": [
733
+ {
734
+ "output_type": "stream",
735
+ "name": "stdout",
736
+ "text": [
737
+ " title sentiment_label \\\n",
738
+ "0 A Light in the Attic positive \n",
739
+ "1 A Light in the Attic positive \n",
740
+ "2 A Light in the Attic positive \n",
741
+ "3 A Light in the Attic positive \n",
742
+ "4 A Light in the Attic positive \n",
743
+ "\n",
744
+ " review_text rating popularity_score \n",
745
+ "0 One of the best books I've read this year β€” in... Three 4 \n",
746
+ "1 Brilliantly written! The characters were unfor... Three 4 \n",
747
+ "2 One of the best books I've read this year β€” in... Three 4 \n",
748
+ "3 One of the best books I've read this year β€” in... Three 4 \n",
749
+ "4 Brilliantly written! The characters were unfor... Three 4 \n"
750
+ ]
751
+ }
752
+ ],
753
+ "source": [
754
+ "print(df_reviews.head())"
755
+ ]
756
+ }
757
+ ],
758
+ "metadata": {
759
+ "colab": {
760
+ "provenance": []
761
+ },
762
+ "kernelspec": {
763
+ "display_name": "Python 3",
764
+ "name": "python3"
765
+ },
766
+ "language_info": {
767
+ "name": "python"
768
+ }
769
+ },
770
+ "nbformat": 4,
771
+ "nbformat_minor": 0
772
+ }
2a_Python_Analysis (2).ipynb ADDED
The diff for this file is too large to render. See raw diff