File size: 54,803 Bytes
d89060d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4ba6aba8"
      },
      "source": [
        "# πŸ€– **Data Collection, Creation, Storage, and Processing**\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jpASMyIQMaAq"
      },
      "source": [
        "## **1.** πŸ“¦ Install required packages"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "f48c8f8c",
        "outputId": "7dfed569-99a5-44c7-b7dd-afabaa3d9257"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
            "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
            "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
            "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
            "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
            "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
            "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
            "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
            "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
            "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
            "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
            "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.61.1)\n",
            "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\n",
            "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
            "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
            "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
            "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
            "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
            "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
            "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
            "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
            "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"
          ]
        }
      ],
      "source": [
        "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lquNYCbfL9IM"
      },
      "source": [
        "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0IWuNpxxYDJF"
      },
      "source": [
        "### *a. Initial setup*\n",
        "Define the base url of the website you will scrape as well as how and what you will scrape"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "91d52125"
      },
      "outputs": [],
      "source": [
        "import requests\n",
        "from bs4 import BeautifulSoup\n",
        "import pandas as pd\n",
        "import time\n",
        "\n",
        "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
        "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
        "\n",
        "titles, prices, ratings = [], [], []"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oCdTsin2Yfp3"
      },
      "source": [
        "### *b. Fill titles, prices, and ratings from the web pages*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "xqO5Y3dnYhxt"
      },
      "outputs": [],
      "source": [
        "# Loop through all 50 pages\n",
        "for page in range(1, 51):\n",
        "    url = base_url.format(page)\n",
        "    response = requests.get(url, headers=headers)\n",
        "    soup = BeautifulSoup(response.content, \"html.parser\")\n",
        "    books = soup.find_all(\"article\", class_=\"product_pod\")\n",
        "\n",
        "    for book in books:\n",
        "        titles.append(book.h3.a[\"title\"])\n",
        "        prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
        "        ratings.append(book.p.get(\"class\")[1])\n",
        "\n",
        "    time.sleep(0.5)  # polite scraping delay"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T0TOeRC4Yrnn"
      },
      "source": [
        "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**First part to complete**"
      ],
      "metadata": {
        "id": "bPhNHyHQ20KI"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "l5FkkNhUYTHh"
      },
      "outputs": [],
      "source": [
        "df_books = pd.DataFrame({\"title\": titles, \"price\": prices, \"rating\": ratings})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "duI5dv3CZYvF"
      },
      "source": [
        "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "lC1U_YHtZifh"
      },
      "outputs": [],
      "source": [
        "# πŸ’Ύ Save to CSV\n",
        "df_books.to_csv(\"books_data.csv\", index=False)\n",
        "\n",
        "# πŸ’Ύ Or save to Excel\n",
        "# df_books.to_excel(\"books_data.xlsx\", index=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qMjRKMBQZlJi"
      },
      "source": [
        "### *e. βœ‹πŸ»πŸ›‘β›”οΈ View first fiew lines*"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Second part to complete**"
      ],
      "metadata": {
        "id": "F54lNj_c3VB2"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 206
        },
        "id": "O_wIvTxYZqCK",
        "outputId": "28f6f57d-c34a-4d52-f473-eede10139889"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "                                   title  price rating\n",
              "0                   A Light in the Attic  51.77  Three\n",
              "1                     Tipping the Velvet  53.74    One\n",
              "2                             Soumission  50.10    One\n",
              "3                          Sharp Objects  47.82   Four\n",
              "4  Sapiens: A Brief History of Humankind  54.23   Five"
            ],
            "text/html": [
              "\n",
              "  <div id=\"df-30f83754-00af-4649-8299-fd130f8cf24c\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>title</th>\n",
              "      <th>price</th>\n",
              "      <th>rating</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>A Light in the Attic</td>\n",
              "      <td>51.77</td>\n",
              "      <td>Three</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Tipping the Velvet</td>\n",
              "      <td>53.74</td>\n",
              "      <td>One</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>Soumission</td>\n",
              "      <td>50.10</td>\n",
              "      <td>One</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>Sharp Objects</td>\n",
              "      <td>47.82</td>\n",
              "      <td>Four</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>Sapiens: A Brief History of Humankind</td>\n",
              "      <td>54.23</td>\n",
              "      <td>Five</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-30f83754-00af-4649-8299-fd130f8cf24c')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-30f83754-00af-4649-8299-fd130f8cf24c button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-30f83754-00af-4649-8299-fd130f8cf24c');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "dataframe",
              "summary": "{\n  \"name\": \"display(df_books\",\n  \"rows\": 5,\n  \"fields\": [\n    {\n      \"column\": \"title\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 5,\n        \"samples\": [\n          \"Tipping the Velvet\",\n          \"Sapiens: A Brief History of Humankind\",\n          \"Soumission\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"price\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 2.647672562837028,\n        \"min\": 47.82,\n        \"max\": 54.23,\n        \"num_unique_values\": 5,\n        \"samples\": [\n          53.74,\n          54.23,\n          50.1\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"rating\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 4,\n        \"samples\": [\n          \"One\",\n          \"Five\",\n          \"Three\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}"
            }
          },
          "metadata": {}
        }
      ],
      "source": [
        "display(df_books.head())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "p-1Pr2szaqLk"
      },
      "source": [
        "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SIaJUGIpaH4V"
      },
      "source": [
        "### *a. Initial setup*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "-gPXGcRPuV_9"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import random\n",
        "from datetime import datetime\n",
        "import warnings\n",
        "\n",
        "warnings.filterwarnings(\"ignore\")\n",
        "random.seed(2025)\n",
        "np.random.seed(2025)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pY4yCoIuaQqp"
      },
      "source": [
        "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "mnd5hdAbaNjz"
      },
      "outputs": [],
      "source": [
        "def generate_popularity_score(rating):\n",
        "    base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
        "    trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
        "    return int(np.clip(base + trend_factor, 1, 5))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "n4-TaNTFgPak"
      },
      "source": [
        "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"popularity_score\" column from \"rating\"*"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Third part to complete**"
      ],
      "metadata": {
        "id": "fP1PDJwE5CdT"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "V-G3OCUCgR07"
      },
      "outputs": [],
      "source": [
        "df_books['popularity_score'] = df_books['rating'].apply(generate_popularity_score)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HnngRNTgacYt"
      },
      "source": [
        "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "id": "kUtWmr8maZLZ"
      },
      "outputs": [],
      "source": [
        "def get_sentiment(popularity_score):\n",
        "    if popularity_score <= 2:\n",
        "        return \"negative\"\n",
        "    elif popularity_score == 3:\n",
        "        return \"neutral\"\n",
        "    else:\n",
        "        return \"positive\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HF9F9HIzgT7Z"
      },
      "source": [
        "### *e. βœ‹πŸ»πŸ›‘β›”οΈ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "id": "tafQj8_7gYCG"
      },
      "outputs": [],
      "source": [
        "df_books['sentiment_label'] = df_books['popularity_score'].apply(get_sentiment)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Fiurth thing to complete (!!)"
      ],
      "metadata": {
        "id": "8yC1FQoe5NQb"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T8AdKkmASq9a"
      },
      "source": [
        "## **4.** πŸ“ˆ Generate synthetic book sales data of 18 months"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OhXbdGD5fH0c"
      },
      "source": [
        "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "id": "qkVhYPXGbgEn"
      },
      "outputs": [],
      "source": [
        "def generate_sales_profile(sentiment):\n",
        "    months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
        "\n",
        "    if sentiment == \"positive\":\n",
        "        base = random.randint(200, 300)\n",
        "        trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
        "    elif sentiment == \"negative\":\n",
        "        base = random.randint(20, 80)\n",
        "        trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
        "    else:  # neutral\n",
        "        base = random.randint(80, 160)\n",
        "        trend = np.full(len(months), base + random.randint(-10, 10))\n",
        "\n",
        "    seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
        "    noise = np.random.normal(0, 5, len(months))\n",
        "    monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
        "\n",
        "    return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L2ak1HlcgoTe"
      },
      "source": [
        "### *b. Run the function as part of building sales_data*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {
        "id": "SlJ24AUafoDB"
      },
      "outputs": [],
      "source": [
        "sales_data = []\n",
        "for _, row in df_books.iterrows():\n",
        "    records = generate_sales_profile(row[\"sentiment_label\"])\n",
        "    for month, units in records:\n",
        "        sales_data.append({\n",
        "            \"title\": row[\"title\"],\n",
        "            \"month\": month,\n",
        "            \"units_sold\": units,\n",
        "            \"sentiment_label\": row[\"sentiment_label\"]\n",
        "        })"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4IXZKcCSgxnq"
      },
      "source": [
        "### *c. βœ‹πŸ»πŸ›‘β›”οΈ Create a df_sales DataFrame from sales_data*\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "wcN6gtiZg-ws"
      },
      "outputs": [],
      "source": [
        "df_sales = pd.DataFrame(sales_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EhIjz9WohAmZ"
      },
      "source": [
        "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "MzbZvLcAhGaH",
        "outputId": "3033960f-762f-4806-9016-09a610aa7f1b"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "                  title    month  units_sold sentiment_label\n",
            "0  A Light in the Attic  2024-09         100         neutral\n",
            "1  A Light in the Attic  2024-10         109         neutral\n",
            "2  A Light in the Attic  2024-11         102         neutral\n",
            "3  A Light in the Attic  2024-12         107         neutral\n",
            "4  A Light in the Attic  2025-01         108         neutral\n"
          ]
        }
      ],
      "source": [
        "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
        "\n",
        "print(df_sales.head())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7g9gqBgQMtJn"
      },
      "source": [
        "## **5.** 🎯 Generate synthetic customer reviews"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Gi4y9M9KuDWx"
      },
      "source": [
        "### *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*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "b3cd2a50"
      },
      "outputs": [],
      "source": [
        "synthetic_reviews_by_sentiment = {\n",
        "    \"positive\": [\n",
        "        \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
        "        \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
        "        \"One of the best books I've read this year β€” inspiring and emotionally rich.\",\n",
        "        \"An absolute page-turner from start to finish.\",\n",
        "        \"The storytelling was captivating and beautifully crafted.\",\n",
        "        \"I couldn't put it down; every chapter pulled me in deeper.\",\n",
        "        \"A masterfully told story with vivid and memorable characters.\",\n",
        "        \"Emotionally powerful and wonderfully executed.\",\n",
        "        \"The author’s writing style is elegant and immersive.\",\n",
        "        \"A truly uplifting and satisfying read.\",\n",
        "        \"This book exceeded all my expectations.\",\n",
        "        \"Rich in detail and full of heart.\",\n",
        "        \"An inspiring story that left me feeling hopeful.\",\n",
        "        \"The pacing was perfect and kept me engaged throughout.\",\n",
        "        \"A fantastic journey that I didn’t want to end.\",\n",
        "        \"Thought-provoking and deeply moving.\",\n",
        "        \"A beautifully imagined world with compelling themes.\",\n",
        "        \"The dialogue felt natural and authentic.\",\n",
        "        \"An unforgettable literary experience.\",\n",
        "        \"Creative, original, and wonderfully written.\",\n",
        "        \"The characters felt real and relatable.\",\n",
        "        \"An engaging plot with satisfying twists.\",\n",
        "        \"I was hooked from the very first page.\",\n",
        "        \"A powerful narrative that resonated with me.\",\n",
        "        \"Smart, insightful, and emotionally rich.\",\n",
        "        \"An entertaining and meaningful story.\",\n",
        "        \"The writing was polished and full of depth.\",\n",
        "        \"A refreshing and unique perspective.\",\n",
        "        \"The emotional impact of this book was incredible.\",\n",
        "        \"A must-read for fans of the genre.\",\n",
        "        \"It balanced humor and heart perfectly.\",\n",
        "        \"A gripping story that kept me invested.\",\n",
        "        \"The themes were explored thoughtfully and effectively.\",\n",
        "        \"An excellent blend of action and character development.\",\n",
        "        \"A deeply satisfying conclusion to a great story.\",\n",
        "        \"Beautiful prose paired with a compelling storyline.\",\n",
        "        \"It left me thinking about it for days.\",\n",
        "        \"An inspiring tale of resilience and growth.\",\n",
        "        \"The atmosphere was vivid and immersive.\",\n",
        "        \"A rewarding and memorable reading experience.\",\n",
        "        \"The author created a world I completely believed in.\",\n",
        "        \"Every chapter added something meaningful.\",\n",
        "        \"A story told with passion and precision.\",\n",
        "        \"Truly a standout book in its category.\",\n",
        "        \"An emotionally satisfying and engaging read.\",\n",
        "        \"The plot twists were surprising yet believable.\",\n",
        "        \"A wonderfully crafted and enjoyable novel.\",\n",
        "        \"It struck the perfect balance between drama and warmth.\",\n",
        "        \"An outstanding work of storytelling.\",\n",
        "        \"A delightful and enriching book overall.\"\n",
        "    ],\n",
        "    \"neutral\": [\n",
        "        \"An average book β€” not great, but not bad either.\",\n",
        "        \"Some parts really stood out, others felt a bit flat.\",\n",
        "        \"It was okay overall. A decent way to pass the time.\",\n",
        "        \"A fairly standard story without many surprises.\",\n",
        "        \"The writing was fine, though not particularly memorable.\",\n",
        "        \"An easy read, but nothing especially remarkable.\",\n",
        "        \"It had its moments, though it didn’t fully captivate me.\",\n",
        "        \"The characters were decent but not very memorable.\",\n",
        "        \"A straightforward plot that delivered what it promised.\",\n",
        "        \"Not my favorite, but not disappointing either.\",\n",
        "        \"The pacing was uneven in places.\",\n",
        "        \"An enjoyable enough read, though somewhat predictable.\",\n",
        "        \"It was mildly interesting but lacked depth.\",\n",
        "        \"A simple story told competently.\",\n",
        "        \"Some chapters were engaging, others less so.\",\n",
        "        \"A solid effort, though it didn’t stand out.\",\n",
        "        \"It met my expectations, but didn’t exceed them.\",\n",
        "        \"The themes were clear but not deeply explored.\",\n",
        "        \"An adequate book for a quiet afternoon.\",\n",
        "        \"The storyline was easy to follow but fairly conventional.\",\n",
        "        \"There were interesting ideas, though not fully developed.\",\n",
        "        \"The writing style was straightforward and clear.\",\n",
        "        \"A mixed experience with highs and lows.\",\n",
        "        \"It started strong but lost momentum midway.\",\n",
        "        \"An acceptable read with room for improvement.\",\n",
        "        \"The ending was satisfactory but not surprising.\",\n",
        "        \"Some aspects worked better than others.\",\n",
        "        \"A predictable but readable story.\",\n",
        "        \"It held my attention, though not consistently.\",\n",
        "        \"The characters were serviceable for the plot.\",\n",
        "        \"An average addition to the genre.\",\n",
        "        \"It had potential that wasn’t fully realized.\",\n",
        "        \"The book was competently written.\",\n",
        "        \"A neutral reading experience overall.\",\n",
        "        \"Not particularly engaging, but not dull either.\",\n",
        "        \"It delivered a standard narrative arc.\",\n",
        "        \"Some emotional moments, though not deeply impactful.\",\n",
        "        \"The setting was interesting but underused.\",\n",
        "        \"An easy but forgettable read.\",\n",
        "        \"It was fine, though I likely won’t revisit it.\",\n",
        "        \"The dialogue was functional but unremarkable.\",\n",
        "        \"A moderately entertaining story.\",\n",
        "        \"It felt balanced but lacked excitement.\",\n",
        "        \"The book maintained a steady tone throughout.\",\n",
        "        \"Neither impressive nor disappointing.\",\n",
        "        \"A passable story with conventional elements.\",\n",
        "        \"It did what it set out to do.\",\n",
        "        \"A readable book without strong highs or lows.\",\n",
        "        \"The plot moved along at a reasonable pace.\",\n",
        "        \"Overall, a fairly ordinary reading experience.\"\n",
        "    ],\n",
        "    \"negative\": [\n",
        "        \"I struggled to get through this one β€” it just didn’t grab me.\",\n",
        "        \"The plot was confusing and the characters felt underdeveloped.\",\n",
        "        \"Disappointing. I had high hopes, but they weren't met.\",\n",
        "        \"The pacing was painfully slow and unfocused.\",\n",
        "        \"I found the story dull and unengaging.\",\n",
        "        \"The writing felt flat and uninspired.\",\n",
        "        \"The characters lacked depth and realism.\",\n",
        "        \"A forgettable and frustrating read.\",\n",
        "        \"The dialogue felt awkward and forced.\",\n",
        "        \"It failed to hold my interest.\",\n",
        "        \"The story seemed disorganized and messy.\",\n",
        "        \"I couldn’t connect with any of the characters.\",\n",
        "        \"The ending was unsatisfying and abrupt.\",\n",
        "        \"The book felt much longer than it needed to be.\",\n",
        "        \"A predictable plot with no real surprises.\",\n",
        "        \"The themes were shallow and poorly executed.\",\n",
        "        \"I found myself skimming just to finish it.\",\n",
        "        \"The narrative lacked clarity and focus.\",\n",
        "        \"An underwhelming and disappointing experience.\",\n",
        "        \"The story never really came together.\",\n",
        "        \"It started poorly and never improved.\",\n",
        "        \"The writing style didn’t appeal to me at all.\",\n",
        "        \"A tedious read from beginning to end.\",\n",
        "        \"The characters’ motivations felt unclear.\",\n",
        "        \"It lacked originality and creativity.\",\n",
        "        \"The plot twists felt forced and unrealistic.\",\n",
        "        \"I expected much more from this author.\",\n",
        "        \"The book felt rushed and incomplete.\",\n",
        "        \"A bland story with little emotional impact.\",\n",
        "        \"The world-building was weak and inconsistent.\",\n",
        "        \"I regret spending time on this book.\",\n",
        "        \"The storyline was repetitive and dull.\",\n",
        "        \"It failed to deliver on its premise.\",\n",
        "        \"The tone felt inconsistent and confusing.\",\n",
        "        \"The book was difficult to stay engaged with.\",\n",
        "        \"The emotional moments felt unearned.\",\n",
        "        \"A frustratingly uneven narrative.\",\n",
        "        \"The characters made unrealistic decisions.\",\n",
        "        \"It didn’t live up to the hype.\",\n",
        "        \"The writing felt overly simplistic.\",\n",
        "        \"The book lacked tension and excitement.\",\n",
        "        \"A poorly executed concept.\",\n",
        "        \"The pacing dragged throughout.\",\n",
        "        \"I found it more irritating than enjoyable.\",\n",
        "        \"The plot holes were distracting.\",\n",
        "        \"An unsatisfying and forgettable novel.\",\n",
        "        \"The storytelling felt amateurish.\",\n",
        "        \"It never fully developed its ideas.\",\n",
        "        \"A disappointing addition to the genre.\",\n",
        "        \"Overall, not a book I would recommend.\"\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fQhfVaDmuULT"
      },
      "source": [
        "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {
        "id": "l2SRc3PjuTGM"
      },
      "outputs": [],
      "source": [
        "review_rows = []\n",
        "for _, row in df_books.iterrows():\n",
        "    title = row['title']\n",
        "    sentiment_label = row['sentiment_label']\n",
        "    review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
        "    sampled_reviews = random.sample(review_pool, 10)\n",
        "    for review_text in sampled_reviews:\n",
        "        review_rows.append({\n",
        "            \"title\": title,\n",
        "            \"sentiment_label\": sentiment_label,\n",
        "            \"review_text\": review_text,\n",
        "            \"rating\": row['rating'],\n",
        "            \"popularity_score\": row['popularity_score']\n",
        "        })"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bmJMXF-Bukdm"
      },
      "source": [
        "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 20,
      "metadata": {
        "id": "ZUKUqZsuumsp"
      },
      "outputs": [],
      "source": [
        "df_reviews = pd.DataFrame(review_rows)\n",
        "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### *c. inputs for R*"
      ],
      "metadata": {
        "id": "_602pYUS3gY5"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3946e521",
        "outputId": "cdf0109a-0720-4a51-9882-77712bb22e9d"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "βœ… Wrote synthetic_title_level_features.csv\n",
            "βœ… Wrote synthetic_monthly_revenue_series.csv\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "\n",
        "def _safe_num(s):\n",
        "    return pd.to_numeric(\n",
        "        pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
        "        errors=\"coerce\"\n",
        "    )\n",
        "\n",
        "# --- Clean book metadata (price/rating) ---\n",
        "df_books_r = df_books.copy()\n",
        "if \"price\" in df_books_r.columns:\n",
        "    df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
        "if \"rating\" in df_books_r.columns:\n",
        "    df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
        "\n",
        "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
        "\n",
        "# --- Clean sales ---\n",
        "df_sales_r = df_sales.copy()\n",
        "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
        "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
        "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
        "\n",
        "# --- Clean reviews ---\n",
        "df_reviews_r = df_reviews.copy()\n",
        "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
        "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
        "if \"rating\" in df_reviews_r.columns:\n",
        "    df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
        "if \"popularity_score\" in df_reviews_r.columns:\n",
        "    df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
        "\n",
        "# --- Sentiment shares per title (from reviews) ---\n",
        "sent_counts = (\n",
        "    df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
        "    .size()\n",
        "    .unstack(fill_value=0)\n",
        ")\n",
        "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
        "    if lab not in sent_counts.columns:\n",
        "        sent_counts[lab] = 0\n",
        "\n",
        "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
        "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
        "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
        "sent_counts[\"share_neutral\"]  = sent_counts[\"neutral\"]  / den\n",
        "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
        "sent_counts = sent_counts.reset_index()\n",
        "\n",
        "# --- Sales aggregation per title ---\n",
        "sales_by_title = (\n",
        "    df_sales_r.dropna(subset=[\"title\"])\n",
        "    .groupby(\"title\", as_index=False)\n",
        "    .agg(\n",
        "        months_observed=(\"month\", \"nunique\"),\n",
        "        avg_units_sold=(\"units_sold\", \"mean\"),\n",
        "        total_units_sold=(\"units_sold\", \"sum\"),\n",
        "    )\n",
        ")\n",
        "\n",
        "# --- Title-level features (join sales + books + sentiment) ---\n",
        "df_title = (\n",
        "    sales_by_title\n",
        "    .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
        "    .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
        "           on=\"title\", how=\"left\")\n",
        ")\n",
        "\n",
        "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
        "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
        "\n",
        "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
        "print(\"βœ… Wrote synthetic_title_level_features.csv\")\n",
        "\n",
        "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
        "monthly_rev = (\n",
        "    df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
        ")\n",
        "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
        "\n",
        "df_monthly = (\n",
        "    monthly_rev.dropna(subset=[\"month\"])\n",
        "    .groupby(\"month\", as_index=False)[\"revenue\"]\n",
        "    .sum()\n",
        "    .rename(columns={\"revenue\": \"total_revenue\"})\n",
        "    .sort_values(\"month\")\n",
        ")\n",
        "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
        "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
        "    df_monthly = (\n",
        "        df_sales_r.dropna(subset=[\"month\"])\n",
        "        .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
        "        .sum()\n",
        "        .rename(columns={\"units_sold\": \"total_revenue\"})\n",
        "        .sort_values(\"month\")\n",
        "    )\n",
        "\n",
        "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
        "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
        "print(\"βœ… Wrote synthetic_monthly_revenue_series.csv\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYvGyVfXuo54"
      },
      "source": [
        "### *d. βœ‹πŸ»πŸ›‘β›”οΈ View the first few lines*"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Last part to complete**"
      ],
      "metadata": {
        "id": "6Ub_snNWKra_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "display(df_books.head())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 206
        },
        "id": "3yDzBL_S3AOw",
        "outputId": "34c6963f-0e45-40e7-c58c-af480f43556b"
      },
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/plain": [
              "                                   title  price rating  popularity_score  \\\n",
              "0                   A Light in the Attic  51.77  Three                 3   \n",
              "1                     Tipping the Velvet  53.74    One                 2   \n",
              "2                             Soumission  50.10    One                 2   \n",
              "3                          Sharp Objects  47.82   Four                 4   \n",
              "4  Sapiens: A Brief History of Humankind  54.23   Five                 3   \n",
              "\n",
              "  sentiment_label  \n",
              "0         neutral  \n",
              "1        negative  \n",
              "2        negative  \n",
              "3        positive  \n",
              "4         neutral  "
            ],
            "text/html": [
              "\n",
              "  <div id=\"df-37551206-2c1b-41a7-b409-da6a6e900bae\" class=\"colab-df-container\">\n",
              "    <div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>title</th>\n",
              "      <th>price</th>\n",
              "      <th>rating</th>\n",
              "      <th>popularity_score</th>\n",
              "      <th>sentiment_label</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>A Light in the Attic</td>\n",
              "      <td>51.77</td>\n",
              "      <td>Three</td>\n",
              "      <td>3</td>\n",
              "      <td>neutral</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Tipping the Velvet</td>\n",
              "      <td>53.74</td>\n",
              "      <td>One</td>\n",
              "      <td>2</td>\n",
              "      <td>negative</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>Soumission</td>\n",
              "      <td>50.10</td>\n",
              "      <td>One</td>\n",
              "      <td>2</td>\n",
              "      <td>negative</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>Sharp Objects</td>\n",
              "      <td>47.82</td>\n",
              "      <td>Four</td>\n",
              "      <td>4</td>\n",
              "      <td>positive</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>Sapiens: A Brief History of Humankind</td>\n",
              "      <td>54.23</td>\n",
              "      <td>Five</td>\n",
              "      <td>3</td>\n",
              "      <td>neutral</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>\n",
              "    <div class=\"colab-df-buttons\">\n",
              "\n",
              "  <div class=\"colab-df-container\">\n",
              "    <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-37551206-2c1b-41a7-b409-da6a6e900bae')\"\n",
              "            title=\"Convert this dataframe to an interactive table.\"\n",
              "            style=\"display:none;\">\n",
              "\n",
              "  <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
              "    <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
              "  </svg>\n",
              "    </button>\n",
              "\n",
              "  <style>\n",
              "    .colab-df-container {\n",
              "      display:flex;\n",
              "      gap: 12px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert {\n",
              "      background-color: #E8F0FE;\n",
              "      border: none;\n",
              "      border-radius: 50%;\n",
              "      cursor: pointer;\n",
              "      display: none;\n",
              "      fill: #1967D2;\n",
              "      height: 32px;\n",
              "      padding: 0 0 0 0;\n",
              "      width: 32px;\n",
              "    }\n",
              "\n",
              "    .colab-df-convert:hover {\n",
              "      background-color: #E2EBFA;\n",
              "      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
              "      fill: #174EA6;\n",
              "    }\n",
              "\n",
              "    .colab-df-buttons div {\n",
              "      margin-bottom: 4px;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert {\n",
              "      background-color: #3B4455;\n",
              "      fill: #D2E3FC;\n",
              "    }\n",
              "\n",
              "    [theme=dark] .colab-df-convert:hover {\n",
              "      background-color: #434B5C;\n",
              "      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
              "      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
              "      fill: #FFFFFF;\n",
              "    }\n",
              "  </style>\n",
              "\n",
              "    <script>\n",
              "      const buttonEl =\n",
              "        document.querySelector('#df-37551206-2c1b-41a7-b409-da6a6e900bae button.colab-df-convert');\n",
              "      buttonEl.style.display =\n",
              "        google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
              "\n",
              "      async function convertToInteractive(key) {\n",
              "        const element = document.querySelector('#df-37551206-2c1b-41a7-b409-da6a6e900bae');\n",
              "        const dataTable =\n",
              "          await google.colab.kernel.invokeFunction('convertToInteractive',\n",
              "                                                    [key], {});\n",
              "        if (!dataTable) return;\n",
              "\n",
              "        const docLinkHtml = 'Like what you see? Visit the ' +\n",
              "          '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
              "          + ' to learn more about interactive tables.';\n",
              "        element.innerHTML = '';\n",
              "        dataTable['output_type'] = 'display_data';\n",
              "        await google.colab.output.renderOutput(dataTable, element);\n",
              "        const docLink = document.createElement('div');\n",
              "        docLink.innerHTML = docLinkHtml;\n",
              "        element.appendChild(docLink);\n",
              "      }\n",
              "    </script>\n",
              "  </div>\n",
              "\n",
              "\n",
              "    </div>\n",
              "  </div>\n"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "dataframe",
              "summary": "{\n  \"name\": \"display(df_books\",\n  \"rows\": 5,\n  \"fields\": [\n    {\n      \"column\": \"title\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 5,\n        \"samples\": [\n          \"Tipping the Velvet\",\n          \"Sapiens: A Brief History of Humankind\",\n          \"Soumission\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"price\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 2.647672562837028,\n        \"min\": 47.82,\n        \"max\": 54.23,\n        \"num_unique_values\": 5,\n        \"samples\": [\n          53.74,\n          54.23,\n          50.1\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"rating\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 4,\n        \"samples\": [\n          \"One\",\n          \"Five\",\n          \"Three\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"popularity_score\",\n      \"properties\": {\n        \"dtype\": \"number\",\n        \"std\": 0,\n        \"min\": 2,\n        \"max\": 4,\n        \"num_unique_values\": 3,\n        \"samples\": [\n          3,\n          2,\n          4\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    },\n    {\n      \"column\": \"sentiment_label\",\n      \"properties\": {\n        \"dtype\": \"string\",\n        \"num_unique_values\": 3,\n        \"samples\": [\n          \"neutral\",\n          \"negative\",\n          \"positive\"\n        ],\n        \"semantic_type\": \"\",\n        \"description\": \"\"\n      }\n    }\n  ]\n}"
            }
          },
          "metadata": {}
        }
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "jpASMyIQMaAq",
        "lquNYCbfL9IM",
        "0IWuNpxxYDJF",
        "oCdTsin2Yfp3",
        "T0TOeRC4Yrnn",
        "duI5dv3CZYvF",
        "qMjRKMBQZlJi",
        "p-1Pr2szaqLk",
        "SIaJUGIpaH4V",
        "pY4yCoIuaQqp",
        "n4-TaNTFgPak",
        "HnngRNTgacYt",
        "HF9F9HIzgT7Z",
        "T8AdKkmASq9a",
        "OhXbdGD5fH0c",
        "L2ak1HlcgoTe",
        "4IXZKcCSgxnq",
        "EhIjz9WohAmZ",
        "Gi4y9M9KuDWx",
        "fQhfVaDmuULT",
        "bmJMXF-Bukdm",
        "RYvGyVfXuo54"
      ],
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}