-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess_data.py
2695 lines (2078 loc) · 106 KB
/
preprocess_data.py
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
import argparse
import collections
import json
import os
import pickle
import warnings
from typing import Any
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from keras.models import model_from_json
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import StandardScaler
# Drop unnecessary columns
def drop_columns(data: pd.DataFrame, config: Dict, expect_target: bool = True) -> pd.DataFrame:
"""
Drops the columns not specified in the provided configuration.
Args:
data: The input DataFrame.
config: Configuration dictionary containing the rules for processing the DataFrame.
expect_target: Optional; default is True. If False, the function will not expect the DataFrame to have the
target column specified in the configuration.
Raises:
ValueError: If a specified column in the configuration is not found in the DataFrame.
ValueError: If the configuration does not contain a 'columns' key.
Returns:
A DataFrame with only the specified columns remaining.
"""
if 'columns' not in config:
raise ValueError("The configuration does not contain a 'columns' key")
specified_columns = config['columns']
if not expect_target and config['target_column'] in specified_columns:
specified_columns.remove(config['target_column'])
for column in specified_columns:
if column not in data.columns:
raise ValueError(
f"Column '{column}' specified in the configuration is not found in the DataFrame")
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Keep only the specified columns
data = data[specified_columns]
return data
# Reorder columns
def reorder_columns(data: pd.DataFrame, config: Dict, ohe_columns_dict: Optional[Dict] = None) -> pd.DataFrame:
"""
Reorders the DataFrame columns according to the provided configuration and one-hot encoding columns dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing the rules for processing the DataFrame.
ohe_columns_dict: A dictionary containing the one-hot encoded columns. Each entry maps a column name to
a dictionary, which contains the list of unique values for the column and the value that was dropped when
the column was one-hot encoded. If this argument is not provided, no changes are made to the column order.
Raises:
ValueError: If the configuration does not contain a 'columns' key.
Returns:
A DataFrame with columns reordered according to the specified column order.
"""
required_keys = ['columns']
# Check if all required keys are in the configuration
if not all(key in config for key in required_keys):
raise ValueError(
f'Configuration must contain the keys {required_keys}')
specified_columns = config['columns'].copy()
# If ohe_columns_dict is provided, modify the specified_columns accordingly
if ohe_columns_dict is not None:
for column, info in ohe_columns_dict.items():
# Remove the original column name from the specified_columns
if column in specified_columns:
specified_columns.remove(column)
# Add the one-hot encoded column names to the specified_columns
for value in info['values']:
if value != info.get('dropped'): # Skip the dropped column
new_column_name = f'{column}_{value}'
specified_columns.append(new_column_name)
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Reorder columns in DataFrame using specified_columns
data = data.reindex(columns=specified_columns)
return data
# Convert to number
def convert_to_number(data: pd.DataFrame, config: Dict) -> pd.DataFrame:
"""
Convert specified DataFrame columns to int or float.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for converting to numbers.
Raises:
ValueError: If the specified column is not found in the data.
ValueError: If the type to convert to is not 'int' or 'float'.
ValueError: If each column configuration does not contain the keys ['column', 'to_type'].
Returns:
The transformed DataFrame.
"""
rules = config['converting_to_number']
required_keys = ['column', 'to_type']
for rule in rules:
# Check if all required keys are in the configuration
if not all(key in rule for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_convert = rule['column']
to_type = rule['to_type']
if column_to_convert not in data.columns:
raise ValueError(f"Column '{column_to_convert}' not found in data")
if to_type not in ['int', 'float']:
raise ValueError(
f"Type '{to_type}' not recognized. Only 'int' and 'float' are supported.")
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Convert column to the desired type
data[column_to_convert] = data[column_to_convert].astype(to_type)
return data
# Apply One-Hot Encoding (OHE)
def apply_one_hot_encoding(data: pd.DataFrame, config: Dict, full_data: pd.DataFrame) -> Tuple[pd.DataFrame, Dict]:
"""
Apply One-Hot Encoding (OHE) to the DataFrame.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for applying one-hot encoding.
full_data: The DataFrame before splitting to the training and testing sets.
Raises:
ValueError: If the specified column is not found in the data.
ValueError: If each column configuration does not contain the keys ['column', 'drop_first'].
Returns:
Tuple containing the transformed DataFrame and a dictionary with the OHE columns.
"""
rules = config['one_hot_encoding']
ohe_columns_dict = {}
most_frequent_value = ''
required_keys = ['column', 'drop_first']
for rule in rules:
# Check if all required keys are in the configuration
if not all(key in rule for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_apply = rule['column']
drop_first = rule['drop_first']
if not column_to_apply:
return data, ohe_columns_dict
if column_to_apply not in full_data.columns:
raise ValueError(
f"Column '{column_to_apply}' not found in full_data")
unique_values = full_data[column_to_apply].unique()
if drop_first:
most_frequent_value = full_data[column_to_apply].value_counts(
).idxmax()
ohe_columns_dict[column_to_apply] = {
'values': unique_values.tolist(), 'dropped': most_frequent_value}
else:
ohe_columns_dict[column_to_apply] = {
'values': unique_values.tolist()}
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Initialize all OHE columns with 0
for value in unique_values:
data[f'{column_to_apply}_{value}'] = 0
# Manual One-Hot Encoding based on unique_values
for value in data[column_to_apply].unique():
data.loc[data[column_to_apply] == value,
f'{column_to_apply}_{value}'] = 1
# Drop the first column if necessary
if drop_first:
data = data.drop(column_to_apply + '_' +
str(most_frequent_value), axis=1)
# Removing original columns from the data
data.drop(column_to_apply, axis=1, inplace=True)
return data, ohe_columns_dict
# Apply One-Hot Encoding (OHE) using dictionary
def apply_one_hot_encoding_using_dict(data: pd.DataFrame, config: Dict, ohe_columns_dict: Dict) -> pd.DataFrame:
"""
Apply One-Hot Encoding (OHE) to the DataFrame using a dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for applying one-hot encoding.
ohe_columns_dict: Dictionary containing the OHE columns from the dictionary.
Raises:
ValueError: If the specified column is not found in the data.
ValueError: If each column configuration does not contain the keys ['column', 'drop_first'].
Returns:
DataFrame with one-hot encoding applied using the specified dictionary.
"""
rules = config['one_hot_encoding']
required_keys = ['column', 'drop_first']
for rule in rules:
# Check if all required keys are in the configuration
if not all(key in rule for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_apply = rule['column']
drop_first = rule['drop_first']
if not column_to_apply:
return data
if column_to_apply not in data.columns:
raise ValueError(f"Column '{column_to_apply}' not found in data")
unique_values = ohe_columns_dict[column_to_apply]['values']
dropped_column = ohe_columns_dict[column_to_apply].get('dropped')
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Initialize all OHE columns with 0
for value in unique_values:
data[f'{column_to_apply}_{value}'] = 0
# If the value exists in the data, set the corresponding OHE column to 1
for value in data[column_to_apply].unique():
data.loc[data[column_to_apply] == value,
f'{column_to_apply}_{value}'] = 1
# Drop the first column if necessary
if drop_first:
data = data.drop(columns=[f'{column_to_apply}_{dropped_column}'])
# Removing original columns from the data
data.drop(column_to_apply, axis=1, inplace=True)
return data
# Fill missing numeric values with zeros
def fill_missing_numeric_values_with_zeros(data: pd.DataFrame, config: Dict) -> pd.DataFrame:
"""
Fill missing numeric values in the DataFrame with zeros.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for filling missing values.
Raises:
ValueError: If the specified column is not found in the data.
Returns:
DataFrame with missing numeric values filled with zeros.
"""
columns_to_fill = config['filling_missing_numeric_values_with_zeroes']
for column in columns_to_fill:
if column not in data.columns:
raise ValueError(f"Column '{column}' not found in data")
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
data[column] = data[column].fillna(0)
return data
# Fill missing numeric values using specified statistical methods
def fill_missing_numeric_values_with_stats_method(data: pd.DataFrame, config: Dict, config_key: str) \
-> Tuple[pd.DataFrame, Dict]:
"""
Fill missing numeric values in the DataFrame using specified statistical methods and save the statistics.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for filling missing values.
config_key: Key to access the specific configuration rules in the config dictionary.
Raises:
ValueError: If the specified column is not found in the data, if an invalid fill_mode is provided,
or if the mode cannot be calculated for a column.
ValueError: If each column configuration does not contain the keys ['column', 'fill_missing_values_method'].
Returns:
Tuple containing the DataFrame with missing numeric values filled and a dictionary with the used statistics.
"""
columns_to_fill = config[config_key]
num_stats_dict = {}
required_keys = ['column', 'fill_missing_values_method']
for column_config in columns_to_fill:
if not column_config:
return data, num_stats_dict
# Check if all required keys are in the configuration
if not all(key in column_config for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_fill = column_config['column']
fill_mode = column_config['fill_missing_values_method']
if column_to_fill not in data.columns:
raise ValueError(f"Column '{column_to_fill}' not found in data")
if not fill_mode:
continue
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if fill_mode == 'mode':
mode_values = data[column_to_fill].mode()
if mode_values.empty:
raise ValueError(
f"Cannot calculate mode for column '{column_to_fill}'")
fill_value = mode_values[0]
elif fill_mode == 'median':
fill_value = data[column_to_fill].median()
elif fill_mode == 'mean':
fill_value = data[column_to_fill].mean()
else:
raise ValueError(
"fill_mode must be one of 'mode', 'median', or 'mean'")
data[column_to_fill] = data[column_to_fill].fillna(fill_value)
# Saving statistics
num_stats_dict[column_to_fill] = fill_value
return data, num_stats_dict
# Fill missing numeric values using dictionary
def fill_missing_numeric_values_with_stats_method_using_dict(data: pd.DataFrame, config: Dict, config_key: str,
num_stats_dict: Dict) -> pd.DataFrame:
"""
Fill missing numeric values in the DataFrame using statistics from the dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for filling missing values.
config_key: Key to access the specific configuration rules in the config dictionary.
num_stats_dict: Dictionary with the statistics used for filling missing values.
Raises:
ValueError: If the specified column is not found in the data.
ValueError: If the required keys are not present in the config dictionary.
Returns:
DataFrame with missing numeric values filled according to the statistics in the dictionary.
"""
columns_to_fill = config[config_key]
required_keys = ['column']
for column_config in columns_to_fill:
if not column_config:
return data
# Check if all required keys are in the configuration
if not all(key in column_config for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_fill = column_config['column']
if column_to_fill not in data.columns:
raise ValueError(f"Column '{column_to_fill}' not found in data")
fill_value = num_stats_dict[column_to_fill]
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Filling missing values using the statistics from the dictionary
data[column_to_fill] = data[column_to_fill].fillna(fill_value)
return data
# Fill missing text values using specified methods
def fill_missing_text_values_with_method(data: pd.DataFrame, config: Dict, config_key: str) \
-> Tuple[pd.DataFrame, Dict]:
"""
Fill missing text values in the DataFrame using specified methods and save the statistics.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for filling missing values.
config_key: Key to access the specific configuration rules in the config dictionary.
Raises:
ValueError: If the specified column is not found in the data, if an invalid fill_method is provided,
if a placeholder is required but not provided, or if the mode cannot be calculated for a column.
ValueError: If the required keys are not present in the config dictionary.
Returns:
Tuple containing the DataFrame with missing text values filled and a dictionary with the used statistics.
"""
columns_to_fill = config[config_key]
text_stats_dict = {}
required_keys = ['column', 'fill_missing_values_method']
for column_config in columns_to_fill:
if not column_config:
return data, text_stats_dict
# Check if all required keys are in the configuration
if not all(key in column_config for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_fill = column_config['column']
fill_method = column_config['fill_missing_values_method']
placeholder = column_config.get('placeholder', '')
if column_to_fill not in data.columns:
raise ValueError(f"Column '{column_to_fill}' not found in data")
if not fill_method:
continue
if fill_method == 'placeholder' and (placeholder is None or placeholder == ''):
raise ValueError(
f"'placeholder' must be specified and not an empty string for column '{column_to_fill}' when"
f"'fill_missing_values_method' is set to 'placeholder'")
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if fill_method == 'mode':
mode_values = data[column_to_fill].mode()
if mode_values.empty:
raise ValueError(
f"Cannot calculate mode for column '{column_to_fill}'")
fill_value = mode_values[0]
elif fill_method == 'placeholder':
fill_value = placeholder
else:
raise ValueError(
"fill_method must be one of 'mode' or 'placeholder'")
data[column_to_fill] = data[column_to_fill].fillna(fill_value)
# Saving statistics
text_stats_dict[column_to_fill] = fill_value
return data, text_stats_dict
# Fill missing text values using dictionary
def fill_missing_text_values_with_method_using_dict(data: pd.DataFrame, config: Dict, config_key: str,
text_stats_dict: Dict) -> pd.DataFrame:
"""
Fill missing text values in the DataFrame using statistics from the dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for filling missing values.
config_key: Key to access the specific configuration rules in the config dictionary.
text_stats_dict: Dictionary with the statistics used for filling missing values.
Raises:
ValueError: If the specified column is not found in the data.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
DataFrame with missing text values filled according to the statistics in the dictionary.
"""
columns_to_fill = config[config_key]
required_keys = ['column']
for column_config in columns_to_fill:
if not column_config:
return data
# Check if all required keys are in the configuration
if not all(key in column_config for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column_to_fill = column_config['column']
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if column_to_fill not in data.columns:
raise ValueError(f"Column '{column_to_fill}' not found in data")
fill_value = text_stats_dict[column_to_fill]
# Filling missing values using the statistics from the dictionary
data[column_to_fill] = data[column_to_fill].fillna(fill_value)
return data
# Remove outliers
def remove_outliers(data: pd.DataFrame, config: Dict) -> Tuple[pd.DataFrame, Dict]:
"""
Remove outliers from the DataFrame and save the thresholds.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for removing outliers.
Raises:
ValueError: If an invalid search_method is provided.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
Tuple containing DataFrame with outliers removed and a dictionary with the used thresholds.
"""
removing_outliers_config = config['removing_outliers']
thresholds_dict = {}
required_keys = ['column', 'search_method']
for config_info in removing_outliers_config:
if not config_info:
return data, thresholds_dict
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
search_method = config_info['search_method']
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if search_method == 'z_score':
threshold = config_info.get('threshold', 3)
z_scores = (data[column] - data[column].mean()) / \
data[column].std()
data = data[np.abs(z_scores) < threshold]
thresholds = {'lower': -threshold, 'upper': threshold}
elif search_method in ['iqr', 'tukey_fences']:
k = config_info.get('k', 1.5 if search_method == 'iqr' else 3.0)
q1 = data[column].quantile(0.25)
q3 = data[column].quantile(0.75)
iqr = q3 - q1
lower_bound = q1 - k * iqr
upper_bound = q3 + k * iqr
data = data[(data[column] > lower_bound) &
(data[column] < upper_bound)]
thresholds = {'lower': lower_bound, 'upper': upper_bound}
else:
raise ValueError(
"search_method must be one of 'z_score', 'iqr', or 'tukey_fences'")
# Saving thresholds
thresholds_dict[column] = {
'bounds': thresholds,
'method': search_method
}
return data, thresholds_dict
# Remove outliers using dictionary
def remove_outliers_using_dict(data: pd.DataFrame, config: Dict, thresholds_dict: Dict) -> pd.DataFrame:
"""
Remove outliers from the test set DataFrame using thresholds from the dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for removing outliers.
thresholds_dict: Dictionary with the thresholds used for removing outliers.
Raises:
ValueError: If any column configuration doesn't contain all required keys.
Returns:
DataFrame with outliers removed according to the thresholds in the dictionary.
"""
removing_outliers_config = config['removing_outliers']
required_keys = ['column']
for config_info in removing_outliers_config:
if not config_info:
return data
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
lower_bound, upper_bound = thresholds_dict[column]['bounds']
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
# Removing outliers using the thresholds from the dictionary
data = data[(data[column] > lower_bound) &
(data[column] < upper_bound)]
return data
# Replace outliers
def replace_outliers(data: pd.DataFrame, config: Dict) -> Tuple[pd.DataFrame, Dict]:
"""
Replace outliers in the DataFrame and save the replacement values.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for replacing outliers.
Raises:
ValueError: If an invalid search_method or replacement_method is provided.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
Tuple containing DataFrame with outliers replaced and a dictionary with the used replacement values.
"""
replacing_outliers_config = config['replacing_outliers']
replacement_values_dict = {}
required_keys = ['column', 'search_method', 'replacement_method']
for config_info in replacing_outliers_config:
if not config_info:
return data, replacement_values_dict
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
search_method = config_info['search_method']
replacement_method = config_info['replacement_method']
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if search_method == 'z_score':
threshold = config_info.get('threshold', 3)
mean = data[column].mean()
std = data[column].std()
lower_bound = mean - threshold * std
upper_bound = mean + threshold * std
outliers = (data[column] < lower_bound) | (
data[column] > upper_bound)
elif search_method in ['iqr', 'tukey_fences']:
k = config_info.get('k', 1.5 if search_method == 'iqr' else 3.0)
q1 = data[column].quantile(0.25)
q3 = data[column].quantile(0.75)
iqr = q3 - q1
lower_bound = q1 - k * iqr
upper_bound = q3 + k * iqr
outliers = (data[column] < lower_bound) | (
data[column] > upper_bound)
else:
raise ValueError(
"search_method must be one of 'z_score', 'iqr', or 'tukey_fences'")
if replacement_method in ['mean', 'median']:
replacement_value = getattr(data[column], replacement_method)()
elif replacement_method == 'mode':
replacement_value = getattr(
data[column], replacement_method)().item()
elif replacement_method == 'quantile_25':
replacement_value = data[column].quantile(0.25)
elif replacement_method == 'quantile_75':
replacement_value = data[column].quantile(0.75)
elif replacement_method in ['lower_bound', 'upper_bound']:
replacement_value = locals()[replacement_method]
else:
raise ValueError("replacement_method must be one of 'mean', 'median', 'mode', 'quantile_25', "
"'quantile_75', 'lower_bound', or 'upper_bound'")
data.loc[outliers, column] = replacement_value
# Saving replacement values
replacement_values_dict[column] = {
'value': replacement_value,
'bounds': (lower_bound, upper_bound),
'method': search_method
}
return data, replacement_values_dict
# Replace outliers using dictionary
def replace_outliers_using_dict(data: pd.DataFrame, config: Dict, replacement_values_dict: Dict) -> pd.DataFrame:
"""
Replace outliers in the DataFrame using replacement values from the dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for replacing outliers.
replacement_values_dict: Dictionary with the replacement values used for replacing outliers.
Raises:
ValueError: If any column configuration doesn't contain all required keys.
Returns:
DataFrame with outliers replaced according to the replacement values in the dictionary.
"""
replacing_outliers_config = config['replacing_outliers']
required_keys = ['column']
for config_info in replacing_outliers_config:
if not config_info:
return data
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
replacement_value = replacement_values_dict[column]['value']
lower_bound, upper_bound = replacement_values_dict[column]['bounds']
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
outliers = (data[column] < lower_bound) | (data[column] > upper_bound)
# Replacing outliers using the replacement values from the dictionary
data.loc[outliers, column] = replacement_value
return data
# Transform data
def transform_data(data: pd.DataFrame, config: Dict) -> Tuple[pd.DataFrame, Dict]:
"""
Transform data in the DataFrame and save the transformation parameters.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for data transformation.
Raises:
ValueError: If an invalid transformation_method is provided or if power is not specified for the 'power' method.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
Tuple containing DataFrame with data transformed and a dictionary with the used transformation parameters.
"""
transformation_config = config['transformation']
transformation_params_dict = {}
required_keys = ['column', 'transformation_method']
for config_info in transformation_config:
if not config_info:
return data, transformation_params_dict
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
transformation_method = config_info['transformation_method']
power = config_info.get('power')
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if transformation_method == 'log':
data[column] = np.log(data[column] + 1) # Adding 1 to avoid log(0)
transformation_params_dict[column] = {
'transformation_method': 'log'}
elif transformation_method == 'sqrt':
data[column] = np.sqrt(data[column])
transformation_params_dict[column] = {
'transformation_method': 'sqrt'}
elif transformation_method == 'power':
if power is None:
raise ValueError(
"Power must be specified for 'power' transformation method")
data[column] = data[column] ** power
transformation_params_dict[column] = {
'transformation_method': 'power', 'power': power}
else:
raise ValueError(
"transformation_method must be one of 'log', 'sqrt', or 'power'")
return data, transformation_params_dict
# Transform data using dictionary
def transform_data_using_dict(data: pd.DataFrame, config: Dict, transformation_params_dict: Dict) -> pd.DataFrame:
"""
Transform data in the DataFrame using transformation parameters from the dictionary.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for data transformation.
transformation_params_dict: Dictionary with the transformation parameters used for data transformation.
Raises:
ValueError: If an invalid transformation_method is provided or if power is not specified for the 'power' method.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
DataFrame with data transformed according to the transformation parameters in the dictionary.
"""
transformation_config = config['transformation']
required_keys = ['column']
for config_info in transformation_config:
if not config_info:
return data
# Check if all required keys are in the configuration
if not all(key in config_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = config_info['column']
transformation_params = transformation_params_dict[column]
transformation_method = transformation_params['transformation_method']
power = transformation_params.get('power')
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
if transformation_method == 'log':
data[column] = np.log(data[column] + 1)
elif transformation_method == 'sqrt':
data[column] = np.sqrt(data[column])
elif transformation_method == 'power':
if power is None:
raise ValueError(
"Power must be specified for 'power' transformation method")
data[column] = data[column] ** power
else:
raise ValueError(
"transformation_method must be one of 'log', 'sqrt', or 'power'")
return data
# Apply Ordinal Encoding
def apply_ordinal_encoding(data: pd.DataFrame, config: Dict) -> pd.DataFrame:
"""
Apply Ordinal Encoding to the DataFrame.
Args:
data: The input DataFrame.
config: Configuration dictionary containing rules for applying ordinal encoding.
Raises:
ValueError: If the specified column is not found in the data or if some values in the column
are not present in the provided ordinal mapping.
ValueError: If the same numeric encoding is assigned to more than one category.
ValueError: If any column configuration doesn't contain all required keys.
Returns:
DataFrame with ordinal encoding applied according to the specified rules.
"""
ordinal_encoding_config = config['ordinal_encoding']
required_keys = ['column', 'mapping']
for encoding_info in ordinal_encoding_config:
if not encoding_info:
return data
# Check if all required keys are in the configuration
if not all(key in encoding_info for key in required_keys):
raise ValueError(
f'Each column configuration must contain the keys {required_keys}')
column = encoding_info['column']
ordinal_mapping = encoding_info['mapping']
# Convert the keys of the ordinal_mapping to match the dtype of the column
column_dtype = data[column].dtype
ordinal_mapping = {column_dtype.type(
k): v for k, v in ordinal_mapping.items()}
if column not in data.columns:
raise ValueError(f"Column '{column}' not found in data")
if not set(data[column].unique()).issubset(set(ordinal_mapping.keys())):
raise ValueError(
f"Some values in '{column}' are not present in the provided ordinal mapping")
# Check for duplicate encoding values
counter = collections.Counter(ordinal_mapping.values())
duplicates = [value for value, count in counter.items() if count > 1]
if duplicates:
raise ValueError(
f"The same numeric encoding {duplicates} is assigned to more than one category in '{column}'. "
f"This will result in data loss as these categories will be merged after encoding. "
f"Please review the encoding rules for this column.")
# Check for category encoded as 0
if 0 in ordinal_mapping.values():
warnings.warn(
f"A category in column '{column}' is encoded as 0. "
f"If 0 does not signify the absence of something, it's generally better to replace it with another "
f"number to avoid potential confusion or issues in subsequent data analysis. "
f"Please review the encoding rules for this column.")
mapped_values = sorted(ordinal_mapping.values())
diff_values = np.diff(mapped_values)
if any(diff_values != 1):
missing_numbers = [mapped_values[i] + j for i,
gap in enumerate(diff_values) for j in range(1, gap)]
warnings.warn(f"The ordinal mapping for '{column}' is missing the following numbers: {missing_numbers}. "
f"This may result in loss of information during encoding. "
f"Please review the encoding rules for this column.")
# Initialize a new DataFrame to avoid SettingWithCopyWarning
data = data.copy()
data[column] = data[column].map(ordinal_mapping)
return data
# Get min and max values
def get_min_max_values(data: pd.DataFrame, column_config: Dict) -> Tuple[float, float]:
"""
Check if the column in DataFrame is numeric and if so, return its minimum and maximum values.