-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_analysis.py
2633 lines (2182 loc) · 94.6 KB
/
data_analysis.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
#!/usr/bin/env python
# Utility Functions to run Jupyter notebooks.
# Dave Babbitt <[email protected]>
# Author: Dave Babbitt, Machine Learning Engineer
# coding: utf-8
# Soli Deo gloria
"""
Run this in a Git Bash terminal if you push anything:
cd ~/OneDrive/Documents/GitHub/notebooks/sh
./update_share_submodules.sh
"""
# Import non-pandas dependencies first
from numpy import nan
from os import path as osp
import math
import numpy as np
import os
# Import pandas components carefully
import pandas as pd
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas.core.reshape.concat import concat
from pandas.core.reshape.encoding import get_dummies
from pandas.core.dtypes.missing import notnull
from pandas.core.tools.datetimes import to_datetime
# Rest of the imports
from re import Pattern, sub
import humanize
import matplotlib.pyplot as plt
import seaborn as sns
import subprocess
from base_config import BaseConfig
# Check if pandas is installed and import relevant functions
try:
from pandas.core.arrays.numeric import is_integer_dtype, is_float_dtype
def is_integer(srs):
"""
Check if the given pandas Series has an integer data type.
Parameters:
srs (pd.Series): A pandas Series to check.
Returns:
bool: True if the Series contains integers, False otherwise.
"""
return is_integer_dtype(srs)
def is_float(srs):
"""
Check if the given pandas Series has a float data type.
Parameters:
srs (pd.Series): A pandas Series to check.
Returns:
bool: True if the Series contains floats, False otherwise.
"""
return is_float_dtype(srs)
except Exception:
def is_integer(srs):
"""
Check if the given list-like object contains integer values.
Parameters:
srs (pd.Series or list): A pandas Series or list-like object to
check.
Returns:
bool: True if any of the values are of integer type, False
otherwise.
"""
return any(map(
lambda value: np.issubdtype(type(value), np.integer), srs.tolist()
))
def is_float(srs):
"""
Check if the given list-like object contains float values.
Parameters:
srs (pd.Series or list): A pandas Series or list-like object to
check.
Returns:
bool: True if any of the values are of float type, False otherwise.
"""
return any(map(lambda value: np.issubdtype(
type(value), np.floating
), srs.tolist()))
class DataAnalysis(BaseConfig):
def __init__(
self, data_folder_path=None, saves_folder_path=None
):
# Assume the data folder exists
if data_folder_path is None:
self.data_folder = osp.join(os.pardir, 'data')
else:
self.data_folder = data_folder_path
# Assume the saves folder exists
if saves_folder_path is None:
self.saves_folder = osp.join(os.pardir, 'saves')
else:
self.saves_folder = saves_folder_path
super().__init__() # Inherit shared attributes
# Color variables
import matplotlib.colors as mcolors
self.xkcd_colors = [
mcolors.hex2color(hex_code)
for hex_code in mcolors.XKCD_COLORS.values()
]
self.nearest_xkcd_name_dict = {
mcolors.hex2color(hex_code): name[5:]
for name, hex_code in mcolors.XKCD_COLORS.items()
}
self.lab_white = (99.99998453333127, -0.0004593894083471106, -0.008561457924405325)
self.lab_gray = (53.38895548925112, -0.0002747978918860028, -0.005121299155619319)
self.lab_black = (0.0, 0.0, 0.0)
# -------------------
# Numeric Functions
# -------------------
# -------------------
# String Functions
# -------------------
# -------------------
# List Functions
# -------------------
# -------------------
# File Functions
# -------------------
@staticmethod
def open_path_in_notepad(
path_str, home_key='USERPROFILE', text_editor_path=None,
continue_execution=True, verbose=True
):
"""
Open a file in Notepad or a specified text editor.
Parameters:
path_str (str): The path to the file to be opened.
home_key (str, optional):
The environment variable key for the home directory. Default
is 'USERPROFILE'.
text_editor_path (str, optional):
The path to the text editor executable. Default is Notepad++.
continue_execution (bool, optional):
If False, interacts with the subprocess and attempts to open
the parent folder in explorer if it gets a bad return code.
Default is True.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
None
Notes:
The function uses subprocess to run the specified text editor
with the provided file path.
Example:
nu.open_path_in_notepad(r'C:\this_example.txt')
"""
# Establish the text_editor_path in this operating system, if needed
if text_editor_path is None:
if os.name == 'nt':
text_editor_path = 'C:\\Program'
text_editor_path += ' Files\\Notepad++\\notepad++.exe'
else:
text_editor_path = '/mnt/c/Program'
text_editor_path += ' Files/Notepad++/notepad++.exe'
# Expand '~' to the home directory in the file path
environ_dict = dict(os.environ)
if '~' in path_str:
if home_key in environ_dict:
path_str = path_str.replace('~', environ_dict[home_key])
else:
path_str = osp.expanduser(path_str)
# Get the absolute path to the file
absolute_path = osp.abspath(path_str)
if os.name != 'nt':
absolute_path = absolute_path.replace(
'/mnt/c/', 'C:\\'
).replace('/', '\\')
if verbose:
print(f'Attempting to open {absolute_path}')
# Open the file in Notepad++ or the specified text editor
cmd = [text_editor_path, absolute_path]
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
if not continue_execution:
out, err = proc.communicate()
if (proc.returncode != 0):
if verbose:
print('Open attempt failed: ' + err.decode('utf8'))
subprocess.run(['explorer.exe', osp.dirname(absolute_path)])
# -------------------
# Path Functions
# -------------------
# -------------------
# Storage Functions
# -------------------
# -------------------
# Module Functions
# -------------------
# -------------------
# URL and Soup Functions
# -------------------
def get_wiki_infobox_data_frame(self, page_titles_list, verbose=True):
"""
Get a DataFrame of key/value pairs from the infobox of Wikipedia
biographical entries.
This function retrieves the infobox data from Wikipedia pages and
constructs a DataFrame where each row corresponds to a page and
each column corresponds to an infobox attribute.
Parameters:
page_titles_list (list of str):
A list of titles of the Wikipedia pages containing the
infoboxes.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to True.
Returns:
pandas.DataFrame
A DataFrame containing the extracted infobox data with page
titles as the first column and infobox labels/values as
separate columns. Returns an empty DataFrame if no data is
found.
Note:
- This function assumes a specific infobox structure and may
require adjustments for different Wikipedia page formats.
- It is assumed that the infobox contains no headers which would
prefix any duplicate labels.
"""
# Import necessary modules not already imported in the class
import wikipedia
# Initialize an empty list to store rows of data
rows_list = []
# Define a helper function to clean text
def clean_text(parent_soup, verbose=False):
# Initialize a list to store text from child elements
texts_list = []
for child_soup in parent_soup.children:
if '{' not in child_soup.text:
# Add stripped text to the list if it doesn't contain '{'
texts_list.append(child_soup.text.strip())
# Join the list of texts into a single string
parent_text = ' '.join(texts_list)
# Trim various enclosing parentheses/brackets of space
for this, with_that in zip(
[' )', ' ]', '( ', '[ '], [')', ']', '(', '[']
):
parent_text = parent_text.replace(this, with_that)
# Remove extra whitespace characters and non-breaking spaces
parent_text = sub('[\\s\\u200b\\xa0]+', ' ', parent_text).strip()
return parent_text
# Use a progress bar if verbose is True
if verbose:
from tqdm import tqdm_notebook as tqdm
page_titles_list = tqdm(page_titles_list)
# Iterate over each page title in the list
for page_title in page_titles_list:
# Initialize a dictionary to store the data for the current page
row_dict = {'page_title': page_title}
try:
# Retrieve the Wikipedia page object
bio_obj = wikipedia.WikipediaPage(title=page_title)
# Get the HTML content of the page
bio_html = bio_obj.html()
# Parse the HTML content using BeautifulSoup
page_soup = bs(bio_html, 'html.parser')
# Find all infobox tables with specific class attributes
infobox_soups_list = page_soup.find_all(
'table', attrs={'class': 'infobox'}
)
# Initialize a list to store labels
labels_list = []
# Iterate over each infobox table
for infobox_soup in infobox_soups_list:
# Find label elements within the infobox
label_soups_list = infobox_soup.find_all('th', attrs={
'scope': 'row', 'class': 'infobox-label',
'colspan': False
})
# Iterate over each label cell
for infobox_label_soup in label_soups_list:
# Clean and format label text, ensuring unique keys
key = self.lower_ascii_regex.sub(
'_', clean_text(infobox_label_soup).lower()
).strip('_')
if key and (key not in labels_list):
# Add the label if it's not a duplicate
labels_list.append(key)
# Find the corresponding value cell
value_soup = infobox_label_soup.find_next(
'td', attrs={'class': 'infobox-data'}
)
# Add the key-value pair to the dictionary
row_dict[key] = clean_text(value_soup)
except Exception as e:
# Continue to the next page if an error occurs
if verbose:
print(
f'{e.__class__.__name__} error processing'
f' {page_title}: {str(e).strip()}'
)
continue
# Add the dictionary to the list of rows
rows_list.append(row_dict)
# Create a dataframe from the list of rows
df = DataFrame(rows_list)
# Return the dataframe
return df
# -------------------
# Pandas Functions
# -------------------
@staticmethod
def get_inf_nan_mask(X_train, y_train):
"""
Return a mask indicating which elements of X_train and y_train are not
inf or nan.
Parameters:
X_train: A NumPy array of numbers.
y_train: A NumPy array of numbers.
Returns:
A numpy array of booleans, where True indicates that the
corresponding element of X_train and y_train is not inf or nan.
This combined mask can be used on both X_train and y_train.
Example:
inf_nan_mask = nu.get_inf_nan_mask(X_train, y_train)
X_train_filtered = X_train[inf_nan_mask]
y_train_filtered = y_train[inf_nan_mask]
"""
# Check if the input lists are empty
if X_train.shape[0] == 0 or y_train.shape[0] == 0:
return np.array([], dtype=bool)
# Create a notnull mask across the X_train and y_train columns
mask_series = concat(
[DataFrame(y_train), DataFrame(X_train)], axis='columns'
).map(notnull).all(axis='columns')
# Return the mask indicating not inf or nan
return mask_series
@staticmethod
def get_column_descriptions(df, analysis_columns=None, verbose=False):
"""
Generate a DataFrame containing descriptive statistics for specified
columns in a given DataFrame.
Parameters:
df (pandas.DataFrame):
The DataFrame to analyze.
analysis_columns (list of str, optional):
A list of specific columns to analyze. If None, all columns
will be analyzed. Defaults to None.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
pandas.DataFrame:
A DataFrame containing the descriptive statistics of the
analyzed columns.
"""
# If analysis_columns not provided, use all columns in the df
if analysis_columns is None:
analysis_columns = df.columns
# Convert the CategoricalDtype instances to strings, then group
grouped_columns = df.columns.to_series().groupby(
df.dtypes.astype(str)
).groups
# Initialize an empty list to store the descriptive statistics rows
rows_list = []
# Iterate over each data type and its corresponding column group
for dtype, dtype_column_list in grouped_columns.items():
for column_name in dtype_column_list:
# Check if the column is in the analysis columns
if column_name in analysis_columns:
# Create a boolean mask for null values in the column
null_mask_series = df[column_name].isnull()
filtered_df = df[~null_mask_series]
# Create a row dictionary to store the column description
row_dict = {
'column_name': column_name,
'dtype': str(dtype),
'count_blanks': df[column_name].isnull().sum()
}
# Count unique values in the column
try:
row_dict['count_uniques'] = df[column_name].nunique()
# Set count of unique values to NaN if an error occurs
except Exception:
row_dict['count_uniques'] = np.nan
# Count the number of zeros
try:
row_dict['count_zeroes'] = int((
df[column_name] == 0
).sum())
# Set count of zeros to NaN if an error occurs
except Exception:
row_dict['count_zeroes'] = np.nan
# Check if the column contains any dates
date_series = to_datetime(
df[column_name], errors='coerce'
)
null_series = date_series[~date_series.notnull()]
null_count = null_series.shape[0]
date_count = date_series.shape[0]
row_dict['has_dates'] = (null_count < date_count)
# Find the minimum value
try:
row_dict['min_value'] = filtered_df[column_name].min()
# Set minimum value to NaN if an error occurs
except Exception:
row_dict['min_value'] = np.nan
# Find the maximum value
try:
row_dict['max_value'] = filtered_df[column_name].max()
# Set maximum value to NaN if an error occurs
except Exception:
row_dict['max_value'] = np.nan
# Check if the column contains only integers
try:
is_integer = df[column_name].apply(
lambda x: float(x).is_integer()
)
row_dict['only_integers'] = is_integer.all()
# Set only_integers to NaN if an error occurs
except Exception:
row_dict['only_integers'] = float('nan')
# Append the row dictionary to the rows list
rows_list.append(row_dict)
# Define column order for the resulting DataFrame
columns_list = [
'column_name', 'dtype', 'count_blanks', 'count_uniques',
'count_zeroes', 'has_dates', 'min_value', 'max_value',
'only_integers'
]
# Create a data frame from the list of dictionaries
blank_ranking_df = DataFrame(rows_list, columns=columns_list)
# Return the data frame containing the descriptive statistics
return blank_ranking_df
@staticmethod
def modalize_columns(df, columns_list, new_column_name):
"""
Create a new column in a DataFrame representing the modal value of
specified columns.
Parameters:
df (pandas.DataFrame): The input DataFrame.
columns_list (list):
The list of column names from which to calculate the modal
value.
new_column_name (str): The name of the new column to create.
Returns:
pandas.DataFrame:
The modified DataFrame with the new column representing the
modal value.
Example:
import numpy as np
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3], 'B': [1.1, 2.2, 3.3], 'C': ['a', 'b', 'c']
})
df['D'] = pd.Series([np.nan, 2, np.nan])
df['E'] = pd.Series([1, np.nan, 3])
df = nu.modalize_columns(df, ['D', 'E'], 'F')
display(df)
assert all(df['A'] == df['F'])
"""
# Ensure that all columns are in the data frame
columns_list = sorted(set(df.columns).intersection(set(columns_list)))
# Create a mask series indicating rows with one unique value across
singular_series = df[columns_list].apply(
Series.nunique, axis='columns'
) == 1
# Check that there is less than two unique column values for all
mask_series = singular_series | (df[columns_list].apply(
Series.nunique, axis='columns'
) < 1)
assert mask_series.all(), (
f'\n\nYou have more than one {new_column_name} in your'
f' columns:\n{df[~mask_series][columns_list]}' # noqa E231
)
# Replace non-unique or missing values with NaN
df.loc[~singular_series, new_column_name] = nan
# Define a function to extract the first valid value in each row
def extract_first_valid_value(srs):
"""
Extract the first valid value from a pandas Series.
Parameters:
srs (pd.Series): A pandas Series object.
Returns:
The first valid value in the Series, or raises an error if no
valid index exists.
"""
return srs[srs.first_valid_index()]
# For identical columns-values rows, set new column to modal value
singular_values = df[singular_series][columns_list]
df.loc[singular_series, new_column_name] = singular_values.apply(
extract_first_valid_value, axis='columns'
)
return df
@staticmethod
def get_regexed_columns(df, search_regex, verbose=False):
"""
Identify columns in a DataFrame that contain references based on a
specified regex pattern.
Parameters:
df (pandas.DataFrame): The input DataFrame.
search_regex (re.Pattern, optional):
The compiled regular expression pattern for identifying
references.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
list:
A list of column names that contain references based on the
specified regex pattern.
"""
# Ensure that the search_regex is a compiled regex object
assert (
isinstance(search_regex, Pattern)
), "search_regex must be a compiled regular expression."
# Print the type of the search_regex if verbose mode is enabled
if verbose:
print(type(search_regex))
# Apply the regex to each element and count occurrences per column
srs = df.map(
lambda x: bool(search_regex.search(str(x))), na_action='ignore'
).sum()
# Extract column names where the count of occurrences is not zero
columns_list = srs[srs != 0].index.tolist()
return columns_list
@staticmethod
def get_regexed_dataframe(
filterable_df, columns_list, search_regex, verbose=False
):
"""
Create a DataFrame that displays an example of what search_regex is
finding for each column in columns_list.
Parameters:
filterable_df (pandas.DataFrame): The input DataFrame to filter.
columns_list (list of str):
The list of column names to investigate for matches.
search_regex (re.Pattern, optional):
The compiled regular expression pattern for identifying
matches. If None, the default pattern for detecting references
will be used.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
pandas.DataFrame:
A DataFrame containing an example row for each column in
columns_list that matches the regex pattern.
"""
# Ensure that all names in columns_list are in there
assert all(
map(lambda cn: cn in filterable_df.columns, columns_list)
), "Column names in columns_list must be in filterable_df.columns"
# Print the debug info if verbose is True
if verbose:
print(type(search_regex))
# Create an empty DataFrame to store the filtered rows
filtered_df = DataFrame([])
# For each column, filter df and extract first row that matches
for cn in columns_list:
# Create a mask to filter rows where column matches pattern
mask_series = filterable_df[cn].map(
lambda x: bool(search_regex.search(str(x)))
)
# Concatenate the first matching row not already in the result
df = filterable_df[mask_series]
mask_series = ~df.index.isin(filtered_df.index)
if mask_series.any():
filtered_df = concat(
[filtered_df, df[mask_series].iloc[0:1]], axis='index'
)
return filtered_df
@staticmethod
def one_hot_encode(df, columns, dummy_na=True):
"""
One-hot encode the specified columns in the provided DataFrame.
This function performs one-hot encoding on a subset of columns
within a DataFrame. One-hot encoding is a technique for
representing categorical variables as binary features. Each
category maps to a new column with a value of 1 for that category
and 0 for all other categories.
Parameters:
df (pandas.DataFrame):
The DataFrame containing the columns to be encoded.
columns (list of str):
A list of column names to encode as one-hot features.
dummy_na (bool, optional):
Whether to add a column to indicate NaNs. Defaults to True.
Returns:
pandas.DataFrame:
A data frame with the encoded columns minus the original
columns.
"""
# Create one-hot encoded representation of the specified columns
dummies = get_dummies(df[columns], dummy_na=dummy_na)
# Create a list of extra dummy variable column names
columns_list = sorted(set(dummies.columns).difference(set(df.columns)))
# Concatenate the data frame with the dummy variables
df = concat([df, dummies[columns_list]], axis='columns')
# Drop the original encoded columns from the DataFrame
df = df.drop(columns, axis='columns')
# Return the DataFrame with the one-hot encoded features
return df
def get_flattened_dictionary(self, value_obj, row_dict={}, key_prefix=''):
"""
Take a value_obj (either a dictionary, list or scalar value) and
create a flattened dictionary from it, where keys are made up of the
keys/indices of nested dictionaries and lists. The keys are
constructed with a key_prefix (which is updated as the function
traverses the value_obj) to ensure uniqueness. The flattened
dictionary is stored in the row_dict argument, which is updated at
each step of the function.
Parameters:
value_obj (dict, list, scalar value):
The object to be flattened into a dictionary.
row_dict (dict, optional):
The dictionary to store the flattened object.
key_prefix (str, optional):
The prefix for constructing the keys in the row_dict.
Returns:
row_dict (dict):
The flattened dictionary representation of the value_obj.
"""
# Check if the value is a dictionary
if isinstance(value_obj, dict):
# Iterate through the dictionary
for k, v, in value_obj.items():
# Recursively call function with dictionary key in prefix
row_dict = self.get_flattened_dictionary(
v, row_dict=row_dict,
key_prefix=f'{key_prefix}{"_" if key_prefix else ""}{k}'
)
# Check if the value is a list
elif isinstance(value_obj, list):
# Get the minimum number of digits in the list length
list_length = len(value_obj)
digits_count = min(len(str(list_length)), 2)
# Iterate through the list
for i, v in enumerate(value_obj):
# Add leading zeros to the index
if i == 0 and list_length == 1:
i = ''
else:
i = str(i).zfill(digits_count)
# Recursively call function with the list index in prefix
row_dict = self.get_flattened_dictionary(
v, row_dict=row_dict, key_prefix=f'{key_prefix}{i}'
)
# If neither a dictionary nor a list, add value to row dictionary
else:
if key_prefix.startswith('_') and key_prefix[1:] not in row_dict:
key_prefix = key_prefix[1:]
row_dict[key_prefix] = value_obj
return row_dict
@staticmethod
def clean_numerics(df, columns_list=None, verbose=False):
import re
if columns_list is None:
columns_list = df.columns
for cn in columns_list:
df[cn] = df[cn].map(lambda x: re.sub(r'[^0-9\.]+', '', str(x)))
df[cn] = pd.to_numeric(df[cn], errors='coerce', downcast='integer')
return df
@staticmethod
def get_numeric_columns(df, is_na_dropped=True):
"""
Identify numeric columns in a DataFrame.
Parameters:
df (pandas.DataFrame):
The DataFrame to search for numeric columns.
is_na_dropped (bool, optional):
Whether to drop columns with all NaN values. Default is True.
Returns:
list
A list of column names containing numeric values.
Notes:
This function identifies numeric columns by checking if the data
in each column can be interpreted as numeric. It checks for
integer, floating-point, and numeric-like objects.
Examples:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3], 'B': [1.1, 2.2, 3.3], 'C': ['a', 'b', 'c']
})
nu.get_numeric_columns(df) # ['A', 'B']
"""
# Initialize an empty list to store numeric column names
numeric_columns = []
# Iterate over DataFrame columns to identify numeric columns
for cn in df.columns:
# Are they are integers or floats?
if is_integer(df[cn]) or is_float(df[cn]):
# Append element to the list
numeric_columns.append(cn)
# Optionally drop columns with all NaN values
if is_na_dropped:
numeric_columns = df[numeric_columns].dropna(
axis='columns', how='all'
).columns
# Sort and return the list of numeric column names
return sorted(numeric_columns)
# -------------------
# 3D Point Functions
# -------------------
@staticmethod
def get_euclidean_distance(first_point, second_point):
"""
Calculate the Euclidean distance between two 2D or 3D points.
This static method calculates the Euclidean distance between two
points (`first_point` and `second_point`). It supports both 2D (x,
y) and 3D (x, y, z) coordinates.
Parameters:
first_point (tuple):
A tuple containing the coordinates of the first point.
second_point (tuple):
A tuple containing the coordinates of the second point.
Returns:
float
The Euclidean distance between the two points, or numpy.nan if
the points have mismatched dimensions.
TODO:
Compare color_distance_from with get_euclidean_distance
"""
# Initialize the Euclidean distance to NaN
euclidean_distance = nan
# Check if both points have the same dimensions (2D or 3D)
assert len(first_point) == len(second_point), (
f'Mismatched dimensions: {len(first_point)}'
f' != {len(second_point)}'
)
# Check if the points are in 3D
if len(first_point) == 3:
# Unpack the coordinates of the first and second points
x1, y1, z1 = first_point
x2, y2, z2 = second_point
# Calculate the Euclidean distance for 3D points
euclidean_distance = math.sqrt(
(x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2
)
# Check if both points are 2D
elif len(first_point) == 2:
# Unpack the coordinates of the first and second points
x1, z1 = first_point
x2, z2 = second_point
# Calculate the Euclidean distance for 2D points
euclidean_distance = math.sqrt((x1 - x2)**2 + (z1 - z2)**2)
# Return the calculated Euclidean distance
return euclidean_distance
def get_nearest_neighbor(self, base_point, neighbors_list):
"""
Get the point nearest in Euclidean distance between two 2D or 3D
points, the base_point and an item from the neighbors_list.
This function finds the neighbor in `neighbors_list` that is
closest (minimum Euclidean distance) to the `base_point`.
Parameters:
base_point (tuple):
A tuple containing the coordinates of the base point.
neighbors_list (list of tuples):
A list of tuples representing the coordinates of neighboring
points.
Returns:
tuple
The coordinates of the nearest neighbor in the
`neighbors_list`, or None if the list is empty.
"""
# Initialize the minimum distance to infinity
min_distance = math.inf
# Initialize the nearest neighbor to None
nearest_neighbor = None
# Iterate over each point in the neighbors list
for neighbor_point in neighbors_list:
# Calculate distance between base point and current neighbor
distance = self.get_euclidean_distance(base_point, neighbor_point)
# Update nearest neighbor/minimum distance if closer one found
if distance < min_distance:
# Update the minimum distance to the calculated distance
min_distance = distance
# Update the nearest neighbor to the current neighbor point
nearest_neighbor = neighbor_point
# Return the nearest neighbor (or None if the list is empty)
return nearest_neighbor
@staticmethod
def move_point_toward(target_point, destination_point, factor=0.1):
"""
Move a point slightly toward a destination point by a given factor.
Parameters:
target_point (np.ndarray):
The point to move (e.g., black or white point).
destination_point (np.ndarray):
The fixed point to move toward.
factor (float):
The proportion of the distance to move.
Returns:
np.ndarray: The new position of the target point.
"""
return target_point + factor * (destination_point - target_point)
@staticmethod
def calculate_spread(points, fixed_point, verbose=False):
"""
Calculate the square root of the sum of the squares of the distances
of a set of points to a fixed point. This is from a mathematical
concept related to the sum of squared distances or similar measures of
dispersion.
Parameters:
points (np.ndarray):