-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwrangle.py
More file actions
1644 lines (1420 loc) · 48.6 KB
/
wrangle.py
File metadata and controls
1644 lines (1420 loc) · 48.6 KB
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
# Standard library imports
import os
import string
from collections import Counter
import ast
# Third-party library imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
import nltk
import ipywidgets as widgets
from IPython.display import display, clear_output
import plotly.express as px
import plotly.graph_objs as go
# Specific functions from those libraries
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import MWETokenizer, word_tokenize
from ipywidgets import interact, widgets
# +------------------------------------------+
# | |
# | D E F I N I N G K E Y W O R D S |
# | |
# +------------------------------------------+
# Picked out keywords based on all keywords (only looked words with 100+ occurrences)
keywords_programming = [
"sql",
"python",
"r",
"c",
"c#",
"javascript",
"js",
"java",
"scala",
"sas",
"matlab",
"c++",
"c/c++",
"perl",
"go",
"typescript",
"bash",
"html",
"css",
"php",
"powershell",
"rust",
"kotlin",
"ruby",
"dart",
"assembly",
"swift",
"vba",
"lua",
"groovy",
"delphi",
"objective-c",
"haskell",
"elixir",
"julia",
"clojure",
"solidity",
"lisp",
"f#",
"fortran",
"erlang",
"apl",
"cobol",
"ocaml",
"crystal",
"javascript/typescript",
"golang",
"nosql",
"mongodb",
"t-sql",
"no-sql",
"visual_basic",
"pascal",
"mongo",
"pl/sql",
"sass",
"vb.net",
"mssql",
]
# Pick out ML Algorithm keywords
keywords_ML_Algorithms = [
x.lower()
for x in [
"regression",
"clustering",
"classification",
"predictive",
"prediction",
"decision trees",
"Decision Trees, Random Forests",
"Convolutional Neural Networks",
"CNN",
"Gradient Boosting Machines (xgboost, lightgbm, etc)",
"Bayesian Approaches",
"Dense Neural Networks (MLPs, etc)",
"DNN",
"Recurrent Neural Networks",
"RNN",
"Transformer Networks (BERT, gpt-3, etc)",
"Graph Neural Networks",
"Transformer" "Autoencoder Networks (DAE, VAE, etc)",
"Generative Adversarial Networks",
"None",
"Evolutionary Approaches",
]
]
# Viz keywords
keyword_viz = [
x.lower()
for x in [
"Matplotlib",
"Seaborn",
"Plotly",
"Ggplot",
"None",
"Shiny",
"Geoplotlib",
"Bokeh",
"D3 js",
"Other",
"Leaflet / Folium",
"Pygal",
"Altair",
"Dygraphs",
"Highcharter",
"tableau",
"Microsoft Power BI",
"Google Data Studio",
"Amazon QuickSight",
"Qlik Sense",
"Other",
"Microsoft Azure Synapse ",
"Looker",
"Alteryx ",
"SAP Analytics Cloud ",
"TIBCO Spotfire",
"Domo",
"Sisense ",
"Thoughtspot ",
]
]
# Computer vision and nlp
keyword_cvnlp = ["computer vision", "natural language processing"]
# Big data keywords
keyword_big_data = [
"mysql",
"postgresql",
"microsoft sql",
"sqlite",
"mongodb",
"bigquery",
"oracle database",
"azure sql",
"amazon rds",
"google cloud sql",
"snowflake",
]
# More big data
keyword_big_data_2 = [
x.lower()
for x in [
"MySQL ",
"PostgreSQL ",
"Microsoft SQL Server ",
"SQLite ",
"MongoDB ",
"None",
"Google Cloud BigQuery ",
"Oracle Database ",
"Microsoft Azure SQL Database ",
"Amazon RDS ",
"Google Cloud SQL ",
"Snowflake ",
"Amazon Redshift ",
"Amazon DynamoDB ",
"Other",
"IBM Db2 ",
]
]
# Business Intelligence keywords
keyword_bi = [
x.lower()
for x in [
"tableau",
"Power BI",
"Power_bi",
"Google Data Studio",
"QuickSight",
"Qlik Sense",
"Other",
"Azure Synapse ",
"Looker",
"Alteryx ",
"SAP Analytics Cloud ",
"TIBCO Spotfire",
"Domo",
"Sisense ",
"Thoughtspot ",
]
]
# More business intelligence
keyword_bi_2 = [
x.lower()
for x in [
"tableau",
"Microsoft Power BI",
"Google Data Studio",
"Amazon QuickSight",
"Qlik Sense",
"Other",
"Microsoft Azure Synapse ",
"Looker",
"Alteryx ",
"SAP Analytics Cloud ",
"TIBCO Spotfire",
"Domo",
"Sisense ",
"Thoughtspot ",
]
]
# Analyst tools
keywords_analyst_tools = [
"excel",
"tableau",
"word",
"powerpoint",
"looker",
"powerbi",
"outlook",
"azure",
"jira",
"twilio",
"snowflake",
"shell",
"linux",
"sas",
"sharepoint",
"mysql",
"visio",
"git",
"mssql",
"powerpoints",
"postgresql",
"spreadsheets",
"seaborn",
"pandas",
"gdpr",
"spreadsheet",
"alteryx",
"github",
"postgres",
"ssis",
"numpy",
"power_bi",
"spss",
"ssrs",
"microstrategy",
"cognos",
"dax",
"matplotlib",
"dplyr",
"tidyr",
"ggplot2",
"plotly",
"esquisse",
"rshiny",
"mlr",
"docker",
"linux",
"jira",
"hadoop",
"airflow",
"redis",
"graphql",
"sap",
"tensorflow",
"node",
"asp.net",
"unix",
"jquery",
"pyspark",
"pytorch",
"gitlab",
"selenium",
"splunk",
"bitbucket",
"qlik",
"terminal",
"atlassian",
"unix/linux",
"linux/unix",
"ubuntu",
"nuix",
"datarobot",
]
# Cloud tools
keywords_cloud_tools = [
"aws",
"azure",
"gcp",
"snowflake",
"redshift",
"bigquery",
"aurora",
"amazon",
"ec2",
"s3",
]
# Not using
keywords_general_tools = [
"microsoft",
"slack",
"apache",
"ibm",
"html5",
"datadog",
"bloomberg",
"ajax",
"persicope",
"oracle",
]
# Not using
keywords_general = [
"coding",
"server",
"database",
"cloud",
"warehousing",
"scrum",
"devops",
"programming",
"saas",
"ci/cd",
"cicd",
"ml",
"data_lake",
"frontend",
" front-end",
"back-end",
"backend",
"json",
"xml",
"ios",
"kanban",
"nlp",
"iot",
"codebase",
"agile/scrum",
"agile",
"ai/ml",
"ai",
"paas",
"machine_learning",
"macros",
"iaas",
"fullstack",
"dataops",
"scrum/agile",
"ssas",
"mlops",
"debug",
"etl",
"a/b",
"slack",
"erp",
"oop",
"object-oriented",
"etl/elt",
"elt",
"dashboarding",
"big-data",
"twilio",
"ui/ux",
"ux/ui",
"vlookup",
"crossover",
"data_lake",
"data_lakes",
"bi",
]
keywords = (
keywords_programming
+ keywords_ML_Algorithms
+ keywords_analyst_tools
+ keywords_cloud_tools
)
# +--------------------------+
# | |
# | P R E P A R A T I O N |
# | |
# +--------------------------+
def tokenize_normalize_lemmatize(text):
# Ensure necessary resources are available
try:
nltk.data.find("tokenizers/punkt")
except LookupError:
nltk.download("punkt")
try:
nltk.data.find("corpora/stopwords")
except LookupError:
nltk.download("stopwords")
# Add 'data' to stopwords
stopwords.words("english").append("data")
lemmatizer = WordNetLemmatizer()
tokens = word_tokenize(text)
# Convert to lowercase, remove punctuation and stopwords, and lemmatize
tokens = [
lemmatizer.lemmatize(word.lower())
for word in tokens
if word.isalpha() and word.lower() not in stopwords.words("english")
]
return tokens
def process_description(description, keywords):
"""
This function processes a job description by tokenizing the words, handling multi-word tokenization,
removing duplicates, filtering for keywords only, and replacing certain keywords.
Parameters:
description (str): The job description to process.
keywords (list): The list of keywords to filter for.
Returns:
list: The processed job description as a list of keywords.
"""
# Convert the description to lowercase
detail = description.lower()
# Tokenize the description into individual words
detail = word_tokenize(detail)
# Define multi-word tokens
multi_tokens = [
("power", "bi"),
("data", "lake"),
("data", "lakes"),
("machine", "learning"),
("objective", "c"),
("visual", "basic"),
("predictive", "prediction"),
("plotly", "express"),
("ggplot", "ggplot"),
("d3", "js"),
]
# Initialize a multi-word tokenizer with the defined tokens
tokenizer = MWETokenizer(multi_tokens)
# Tokenize the description with the multi-word tokenizer
detail = tokenizer.tokenize(detail)
# Remove duplicate words
detail = list(set(detail))
# Filter the description for the specified keywords
detail = [word for word in detail if word in keywords]
# Define tokens to replace
replace_tokens = {"powerbi": "power_bi", "spreadsheets": "spreadsheet"}
# Replace the defined tokens in the description
for key, value in replace_tokens.items():
detail = [d.replace(key, value) for d in detail]
# Replace "c/c++" and "c++" with "c++"
detail = ["c++" if skill in ["c/c++", "c++"] else skill for skill in detail]
return detail
def prepare_jobs(jobs_df_cleaned):
"""
1. Selects a subset of columns from the DataFrame.
2. Drops duplicate rows based on the "job_id" column.
3. Drops the "job_id" column.
4. Fills null values in the "work_from_home" column with False.
5. Creates a new "cleaned_salary" column and performs several transformations on it
to standardize the salary information.
6. Extracts the pay rate from the "cleaned_salary" column.
7. Drops all letters from the "cleaned_salary" column.
8. Splits the "cleaned_salary" into "min_salary" and "max_salary" columns.
9. Creates an "avg_salary" column by averaging the "min_salary" and "max_salary" columns.
10. Adjusts the salary columns based on the pay rate.
11. Drops the original "salary" column.
12. Cleans the "location" column and replaces state abbreviations with full names.
13. Renames the "date_time" column to "date_scraped" and converts it to datetime.
14. Converts the "posted_at" column to a timedelta.
15. Creates a new "posting_created" column by subtracting "posted_at" from "date_scraped".
16. Standardizes the job titles in the "title" column.
17. Tokenizes the job descriptions and filters for certain keywords.
18. Creates a new 'sector' column based on certain keywords in the 'description' column.
19. Filters the DataFrame to only include full-time jobs.
Parameters:
df (DataFrame): The input DataFrame.
Returns:
A prepped dataframe
"""
file_path = "./support_files/prepped_jobs.csv"
if os.path.isfile(file_path):
# Read in CSV
jobs_df_cleaned = pd.read_csv(file_path)
# Convert the strings in 'description_cleaned' and 'description_tokens' back into lists
jobs_df_cleaned["description_cleaned"] = jobs_df_cleaned[
"description_cleaned"
].apply(ast.literal_eval)
jobs_df_cleaned["description_tokens"] = jobs_df_cleaned[
"description_tokens"
].apply(ast.literal_eval)
# Make the index date time
jobs_df_cleaned.index = pd.to_datetime(jobs_df_cleaned["posting_created"])
return jobs_df_cleaned
else:
# Drop duplicates on the unique identifier
jobs_df_cleaned.drop_duplicates(subset=["job_id"], inplace=True)
# Drop the column since we're not using it anymore
jobs_df_cleaned = jobs_df_cleaned.drop(columns=["job_id"])
# Fill nulls in work from home with False
jobs_df_cleaned["work_from_home"] = jobs_df_cleaned["work_from_home"].fillna(
False
)
# Create a salary cleaned column out of a copy of salary
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned["salary"]
# Remove decimals and numeric character until you hit a - or [a-zA-Z]
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned[
"cleaned_salary"
].str.replace(r"\.\d+(?=[a-zA-Z-])", "", regex=True)
# Replace 'K' or 'k' in the 'cleaned_salary' column with ',000'
jobs_df_cleaned["cleaned_salary"] = (
jobs_df_cleaned["cleaned_salary"]
.str.replace("K", "000", case=False, regex=True)
.str.replace("k", "000", case=False, regex=True)
)
# Remove commas from all entries in the 'cleaned_salary' column
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned[
"cleaned_salary"
].str.replace(",", "", regex=False)
# Extract pay rate
jobs_df_cleaned["pay_rate"] = jobs_df_cleaned["cleaned_salary"].str.extract(
r"(\bhour\b|\bmonth\b|\byear\b)", expand=False
)
# Add "ly" to the entire column
jobs_df_cleaned["pay_rate"] = jobs_df_cleaned["pay_rate"].str.replace(
r"(\bhour\b|\bmonth\b|\byear\b)", r"\1ly", regex=True
)
# Drop all letters from salary cleaned column
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned[
"cleaned_salary"
].str.replace(r"[a-zA-Z]", "", regex=True)
# Function to get min salary
def get_min_salary(salary):
return salary.split("–")[0]
# Function to get max salary
def get_max_salary(salary):
values = salary.split("–")
if len(values) == 1:
return values[0]
return values[1]
# Make salary cleaned a string
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned["cleaned_salary"].astype(
str
)
# Apply the functions to get min_salary and max_salary columns
jobs_df_cleaned["min_salary"] = jobs_df_cleaned["cleaned_salary"].apply(
get_min_salary
)
jobs_df_cleaned["max_salary"] = jobs_df_cleaned["cleaned_salary"].apply(
get_max_salary
)
# Make an avg_salary column using the average of min and max
jobs_df_cleaned["avg_salary"] = (
jobs_df_cleaned["min_salary"].astype(float)
+ jobs_df_cleaned["max_salary"].astype(float)
) / 2
# If pay rate is hourly, multiply min_salary, max_salary, and avg_salary by 2080
jobs_df_cleaned.loc[
jobs_df_cleaned["pay_rate"] == "hourly",
["min_salary", "max_salary", "avg_salary"],
] = (
jobs_df_cleaned.loc[
jobs_df_cleaned["pay_rate"] == "hourly",
["min_salary", "max_salary", "avg_salary"],
].astype(float)
* 2080
)
# If pay rate is monthly, multiply min_salary, max_salary, and avg_salary by 12
jobs_df_cleaned.loc[
jobs_df_cleaned["pay_rate"] == "monthly",
["min_salary", "max_salary", "avg_salary"],
] = (
jobs_df_cleaned.loc[
jobs_df_cleaned["pay_rate"] == "monthly",
["min_salary", "max_salary", "avg_salary"],
].astype(float)
* 12
)
# Drop the old salary
jobs_df_cleaned = jobs_df_cleaned.drop(columns=["salary"])
# Make them floats
jobs_df_cleaned["min_salary"] = jobs_df_cleaned["min_salary"].astype(float)
jobs_df_cleaned["max_salary"] = jobs_df_cleaned["max_salary"].astype(float)
# Replace "nan" in cleaned_salary with nulls
jobs_df_cleaned["cleaned_salary"] = jobs_df_cleaned["cleaned_salary"].replace(
"nan", np.nan
)
# Make the column a string
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned["location"].astype(str)
# Make a lambda for all the states and apply it to a state column, to reduce location values
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned["location_cleaned"].apply(
lambda x: x.split(",")[1].strip() if "," in x else x
)
# Create a dictionary with state abbreviations and full names
state_dict = {
"CA": "California",
"NY": "New York",
"NJ": "New Jersey",
"MO": "Missouri",
"OK": "Oklahoma",
"KS": "Kansas",
"AR": "Arkansas",
"TX": "Texas",
"MA": "Massachusetts",
"NE": "Nebraska",
"PA": "Pennsylvania",
"DC": "District of Columbia",
"CT": "Connecticut",
"NH": "New Hampshire",
}
# Replace state abbreviations with full names
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned[
"location_cleaned"
].replace(state_dict)
# If the string has (+X others), change it to "Multiple Locations"
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned["location_cleaned"].apply(
lambda x: "Multiple Locations" if "(" in x else x
)
# Remove leading and trailing white space
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned[
"location_cleaned"
].str.strip()
# Replace "nan" with Unkown
jobs_df_cleaned["location_cleaned"] = jobs_df_cleaned[
"location_cleaned"
].replace("nan", "Unknown")
# Change date_time to date_scraped
jobs_df_cleaned.rename(columns={"date_time": "date_scraped"}, inplace=True)
# Convert "posted_at" to timedelta
jobs_df_cleaned["posted_at"] = pd.to_timedelta(
jobs_df_cleaned["posted_at"].str.extract("(\d+)")[0].astype(int), unit="h"
)
# Convert "date_scraped" to datetime
jobs_df_cleaned["date_scraped"] = pd.to_datetime(
jobs_df_cleaned["date_scraped"]
)
# Create "posting_created" column
jobs_df_cleaned["posting_created"] = (
jobs_df_cleaned["date_scraped"] - jobs_df_cleaned["posted_at"]
)
# Change posting_created to be date time formated with only hours and minutes
jobs_df_cleaned["posting_created"] = jobs_df_cleaned[
"posting_created"
].dt.strftime("%Y-%m-%d %H:%M")
# Make the index date time
jobs_df_cleaned.index = pd.to_datetime(jobs_df_cleaned["posting_created"])
# Define the mapping of keywords to standardized titles
title_mapping = {
"scie": "Data Scientist",
"eng": "Data Engineer",
"ana": "Data Analyst",
}
# Apply the mapping to the 'title' column
jobs_df_cleaned["title_cleaned"] = jobs_df_cleaned["title"].apply(
lambda x: next((v for k, v in title_mapping.items() if k in x.lower()), x)
)
# If a title_cleaned isn't one of those 3, make it Other
jobs_df_cleaned["title_cleaned"] = jobs_df_cleaned["title_cleaned"].apply(
lambda x: "Other" if x not in title_mapping.values() else x
)
# Drop "Other" title_cleaned
jobs_df_cleaned = jobs_df_cleaned[jobs_df_cleaned["title_cleaned"] != "Other"]
jobs_df_cleaned["description_cleaned"] = jobs_df_cleaned["description"].apply(
tokenize_normalize_lemmatize
)
jobs_df_cleaned["description_tokens"] = jobs_df_cleaned["description"].apply(
lambda x: process_description(x, keywords)
)
# List of words to remove
words_to_remove = ["data", "experience", "business", "work"]
# Function to remove specific words
def remove_words(word_list):
return [word for word in word_list if word not in words_to_remove]
jobs_df_cleaned["description_cleaned"] = jobs_df_cleaned[
"description_cleaned"
].apply(remove_words)
# If the schedule type does not have "Full-time", drop it
jobs_df_cleaned = jobs_df_cleaned[
jobs_df_cleaned["schedule_type"] == "Full-time"
]
# Play a sound when completed
os.system("afplay /System/Library/Sounds/Ping.aiff")
return jobs_df_cleaned
def check_columns(DataFrame, reports=False, graphs=False, dates=False):
"""
This function takes a pandas dataframe as input and returns
a dataframe with information about each column in the dataframe.
"""
dataframeinfo = []
# Check information about the index
index_dtype = DataFrame.index.dtype
index_unique_vals = DataFrame.index.unique()
index_num_unique = DataFrame.index.nunique()
index_num_null = DataFrame.index.isna().sum()
index_pct_null = index_num_null / len(DataFrame.index)
if pd.api.types.is_numeric_dtype(index_dtype) and not isinstance(
DataFrame.index, pd.RangeIndex
):
index_min_val = DataFrame.index.min()
index_max_val = DataFrame.index.max()
index_range_vals = (index_min_val, index_max_val)
elif pd.api.types.is_datetime64_any_dtype(index_dtype):
index_min_val = DataFrame.index.min()
index_max_val = DataFrame.index.max()
index_range_vals = (
index_min_val.strftime("%Y-%m-%d"),
index_max_val.strftime("%Y-%m-%d"),
)
# Check for missing dates in the index if dates kwarg is True
if dates:
full_date_range = pd.date_range(
start=index_min_val, end=index_max_val, freq="D"
)
missing_dates = full_date_range.difference(DataFrame.index)
if not missing_dates.empty:
print(
f"Missing dates in index: ({len(missing_dates)} Total) {missing_dates.tolist()}"
)
else:
index_range_vals = None
dataframeinfo.append(
[
"index",
index_dtype,
index_num_unique,
index_num_null,
index_pct_null,
index_unique_vals,
index_range_vals,
]
)
print(f"Total rows: {DataFrame.shape[0]}")
print(f"Total columns: {DataFrame.shape[1]}")
if reports:
describe = DataFrame.describe().round(2)
print(describe)
if graphs:
DataFrame.hist(figsize=(10, 10))
plt.subplots_adjust(hspace=0.5)
plt.show()
for column in DataFrame.columns:
dtype = DataFrame[column].dtype
num_null = DataFrame[column].isna().sum()
pct_null = DataFrame[column].isna().mean().round(5)
try:
unique_vals = DataFrame[column].unique()
num_unique = DataFrame[column].nunique()
except TypeError:
unique_vals = "Column contains multiple lists"
num_unique = "ERROR"
if pd.api.types.is_numeric_dtype(dtype):
min_val = DataFrame[column].min()
max_val = DataFrame[column].max()
mean_val = DataFrame[column].mean()
range_vals = (min_val, max_val, mean_val)
elif pd.api.types.is_datetime64_any_dtype(dtype):
min_val = DataFrame[column].min()
max_val = DataFrame[column].max()
range_vals = (min_val.strftime("%Y-%m-%d"), max_val.strftime("%Y-%m-%d"))
if dates:
full_date_range_col = pd.date_range(
start=min_val, end=max_val, freq="D"
)
missing_dates_col = full_date_range_col.difference(DataFrame[column])
if not missing_dates_col.empty:
print(
f"Missing dates in column '{column}': ({len(missing_dates_col)} Total) {missing_dates_col.tolist()}"
)
else:
print(f"No missing dates in column '{column}'")
else:
range_vals = None
dataframeinfo.append(
[column, dtype, num_unique, num_null, pct_null, unique_vals, range_vals]
)
return pd.DataFrame(
dataframeinfo,
columns=[
"col_name",
"dtype",
"num_unique",
"num_null",
"pct_null",
"unique_values",
"range (min, max, mean)",
],
)
def preprocess_jobs_df(jobs_df):
import pandas as pd
import numpy as np
import nltk
from nltk.tokenize import word_tokenize, MWETokenizer
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from collections import Counter
# Ensure necessary resources are available
nltk.download("punkt")
nltk.download("stopwords")
# Define helper functions
def get_min_salary(salary):
return salary.split("–")[0]
def get_max_salary(salary):
values = salary.split("–")
if len(values) == 1:
return values[0]
return values[1]
def standardize_titles(df):
title_mapping = {
"scie": "Data Scientist",
"eng": "Data Engineer",
"ana": "Data Analyst",
}
df["title_cleaned"] = df["title"].apply(
lambda x: next((v for k, v in title_mapping.items() if k in x.lower()), x)
)
df["title_cleaned"] = df["title_cleaned"].apply(
lambda x: "Other" if x not in title_mapping.values() else x
)
return df
def tokenize_normalize_lemmatize(text):
lemmatizer = WordNetLemmatizer()
tokens = word_tokenize(text)
tokens = [
lemmatizer.lemmatize(word.lower())
for word in tokens
if word.isalpha() and word.lower() not in stopwords.words("english")
]
return tokens
def process_description(description, keywords):
detail = description.lower()
detail = word_tokenize(detail)
multi_tokens = [
("power", "bi"),
("data", "lake"),
("data", "lakes"),
("machine", "learning"),
("objective", "c"),
("visual", "basic"),
("predictive", "prediction"),
("plotly", "express"),
("ggplot", "ggplot"),
("d3", "js"),
]
tokenizer = MWETokenizer(multi_tokens)
detail = tokenizer.tokenize(detail)
detail = list(set(detail))
detail = [word for word in detail if word in keywords]
replace_tokens = {"powerbi": "power_bi", "spreadsheets": "spreadsheet"}
for key, value in replace_tokens.items():
detail = [d.replace(key, value) for d in detail]
detail = ["c++" if skill in ["c/c++", "c++"] else skill for skill in detail]
return detail
def create_sector_column(df):
sector_mapping = {
"finance": "Finance",
"business": "Business",
"healthcare": "Healthcare",
"patient": "Healthcare",
"technology": "Technology",
"education": "Education",
"retail": "Retail",
"property": "Real Estate",
}
df["sector"] = df["description_cleaned"].apply(
lambda x: next(
(v for k, v in sector_mapping.items() if k in " ".join(x).lower()),
"Other",
)
)
return df
# Start preprocessing
jobs_df_cleaned = jobs_df[
[
"title",
"company_name",
"location",
"via",
"description",
"posted_at",
"schedule_type",
"work_from_home",
"salary",
"job_id",
"date_time",
"salary_pay",