-
Notifications
You must be signed in to change notification settings - Fork 147
/
base.py
721 lines (571 loc) · 26.1 KB
/
base.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
# Author: Niels Nuyttens <niels@nannyml.com>
#
# License: Apache Software License 2.0
"""Module containing base classes for drift calculation."""
from __future__ import annotations
import copy
import logging
from abc import ABC, abstractmethod
from typing import Generic, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, overload
import numpy as np
import pandas as pd
import plotly.graph_objects
from nannyml._typing import Key, Metric, Result, Self
from nannyml.chunk import Chunker, ChunkerFactory
from nannyml.exceptions import CalculatorException, EstimatorException, InvalidArgumentsException, NannyMLException
MetricLike = TypeVar('MetricLike', bound=Metric)
class AbstractResult(ABC):
"""Contains the results of a calculation and provides plotting functionality.
The result of the :meth:`~nannyml.base.AbstractCalculator.calculate` method of a
:class:`~nannyml.base.AbstractCalculator`.
It is an abstract class containing shared properties and methods across implementations.
For each :class:`~nannyml.base.AbstractCalculator` class there will be a corresponding
:class:`~nannyml.base.AbstractCalculatorResult` implementation.
"""
DEFAULT_COLUMNS = ('key', 'chunk_index', 'start_index', 'end_index', 'start_date', 'end_date', 'period')
def __init__(self, results_data: pd.DataFrame, *args, **kwargs):
"""Creates a new :class:`~nannyml.base.AbstractCalculatorResult` instance.
Parameters
----------
results_data: pd.DataFrame
The data returned by the Calculator.
"""
self.data = results_data.copy(deep=True)
@property
def _logger(self) -> logging.Logger:
return logging.getLogger(__name__)
@property
def empty(self) -> bool:
return self.data is None or self.data.empty
# TODO: define more specific interface (add common arguments)
def __len__(self): # noqa: D105
return len(self.data)
@abstractmethod
def plot(self, *args, **kwargs) -> plotly.graph_objects.Figure:
"""Plots calculation results."""
raise NotImplementedError
def to_df(self, multilevel: bool = True) -> pd.DataFrame:
"""Export results to pandas dataframe."""
if multilevel:
return self.data
else:
column_names = [
'_'.join(col).replace('chunk_chunk_chunk', 'chunk').replace('chunk_chunk', 'chunk')
for col in self.data.columns.values
]
single_level_data = self.data.copy(deep=True)
single_level_data.columns = column_names
return single_level_data
def filter(self, period: str = 'all', metrics: Optional[Union[str, List[str]]] = None, *args, **kwargs) -> Self:
"""Returns filtered result metric data."""
if metrics and not isinstance(metrics, (str, list)):
raise InvalidArgumentsException("metrics value provided is not a valid metric or list of metrics")
if isinstance(metrics, str):
metrics = [metrics]
try:
return self._filter(period, metrics, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise CalculatorException(f"could not read result data: {exc}")
@abstractmethod
def _filter(self, period: str, metrics: Optional[List[str]] = None, *args, **kwargs) -> Self:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the '_filter' method")
@abstractmethod
def keys(self) -> List[Key]:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the 'items' method")
def values(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='value')
def alerts(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='alert')
def upper_thresholds(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='upper_threshold')
def lower_thresholds(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='lower_threshold')
def upper_confidence_bounds(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='upper_confidence_boundary')
def lower_confidence_bounds(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='lower_confidence_boundary')
def sampling_error(self, key: Key) -> Optional[pd.Series]:
return self._get_property_for_key(key, property_name='sampling_error')
def _get_property_for_key(self, key: Key, property_name: str) -> Optional[pd.Series]:
return self.data.get(key.properties + (property_name,), default=None)
class Abstract1DResult(AbstractResult, ABC):
def __init__(self, results_data: pd.DataFrame, *args, **kwargs):
super().__init__(results_data)
@property
def chunk_keys(self) -> pd.Series:
return self.data[('chunk', 'key')]
@property
def chunk_start_dates(self) -> pd.Series:
return self.data[('chunk', 'start_date')]
@property
def chunk_end_dates(self) -> pd.Series:
return self.data[('chunk', 'end_date')]
@property
def chunk_start_indices(self) -> pd.Series:
return self.data[('chunk', 'start_index')]
@property
def chunk_end_indices(self) -> pd.Series:
return self.data[('chunk', 'end_index')]
@property
def chunk_indices(self) -> pd.Series:
return self.data[('chunk', 'chunk_index')]
@property
def chunk_periods(self) -> pd.Series:
return self.data[('chunk', 'period')]
@property
def chunk_start_index(self) -> pd.Series:
return self.data[('chunk', 'start_index')]
def _filter(self, period: str, *args, **kwargs) -> Self:
data = self.data
if period != 'all':
data = self.data.loc[self.data.loc[:, ('chunk', 'period')] == period, :]
data = data.reset_index(drop=True)
res = copy.deepcopy(self)
res.data = data
return res
class PerMetricResult(Abstract1DResult, ABC, Generic[MetricLike]):
def __init__(self, results_data: pd.DataFrame, metrics: list[MetricLike] = [], *args, **kwargs):
super().__init__(results_data)
self.metrics = metrics
def _filter(self, period: str, metrics: Optional[List[str]] = None, *args, **kwargs) -> Self:
if metrics is None:
metrics = [metric.column_name for metric in self.metrics]
res = super()._filter(period, *args, **kwargs)
data = pd.concat([res.data.loc[:, (['chunk'])], res.data.loc[:, (metrics,)]], axis=1)
data = data.reset_index(drop=True)
res.data = data
res.metrics = [metric for metric in self.metrics if metric.column_name in metrics]
return res
class PerColumnResult(Abstract1DResult, ABC):
def __init__(self, results_data: pd.DataFrame, column_names: Union[str, List[str]] = [], *args, **kwargs):
super().__init__(results_data)
if isinstance(column_names, str):
self.column_names = [column_names]
elif isinstance(column_names, list):
self.column_names = column_names
else:
raise TypeError("column_names should be either a column name string or a list of strings.")
def _filter(
self,
period: str,
metrics: Optional[List[str]] = None,
column_names: Optional[Union[str, List[str]]] = None,
*args,
**kwargs,
) -> Self:
if isinstance(column_names, str):
column_names = [column_names]
elif isinstance(column_names, list):
pass
elif column_names is None:
column_names = self.column_names
else:
raise TypeError("column_names should be either a column name string or a list of strings.")
res = super()._filter(period, *args, **kwargs)
data = pd.concat([res.data.loc[:, (['chunk'])], res.data.loc[:, (column_names,)]], axis=1)
data = data.reset_index(drop=True)
res.data = data
res.column_names = [c for c in self.column_names if c in column_names]
return res
class Abstract2DResult(AbstractResult, ABC):
def __init__(self, results_data: pd.DataFrame, *args, **kwargs):
super().__init__(results_data)
@property
def chunk_keys(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'key')]
@property
def chunk_start_dates(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'start_date')]
@property
def chunk_end_dates(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'end_date')]
@property
def chunk_start_indices(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'start_index')]
@property
def chunk_end_indices(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'end_index')]
@property
def chunk_indices(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'chunk_index')]
@property
def chunk_periods(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'period')]
@property
def chunk_start_index(self) -> pd.Series:
return self.data[('chunk', 'chunk', 'start_index')]
def _filter(
self,
period: str,
*args,
**kwargs,
) -> Self:
data = self.data
if period != 'all':
data = data.loc[self.data.loc[:, ('chunk', 'chunk', 'period')] == period, :]
data = data.reset_index(drop=True)
res = copy.deepcopy(self)
res.data = data
return res
class PerMetricPerColumnResult(Abstract2DResult, ABC, Generic[MetricLike]):
def __init__(
self, results_data: pd.DataFrame, metrics: list[MetricLike] = [], column_names: List[str] = [], *args, **kwargs
):
super().__init__(results_data)
self.metrics = metrics
self.column_names = column_names
def _filter(
self,
period: str,
metrics: Optional[List[str]] = None,
column_names: Optional[List[str]] = None,
*args,
**kwargs,
) -> Self:
res = super()._filter(period, *args, **kwargs)
if metrics is None and column_names is None:
return res
if metrics is None:
metrics = [metric.column_name for metric in self.metrics]
if column_names is None:
column_names = self.column_names
data = pd.concat([res.data.loc[:, (['chunk'])], res.data.loc[:, (column_names, metrics)]], axis=1)
data = data.reset_index(drop=True)
res.data = data
res.metrics = [metric for metric in self.metrics if metric.column_name in metrics]
res.column_names = [c for c in self.column_names if c in column_names]
return res
class AbstractCalculator(ABC):
"""Base class for drift calculation."""
def __init__(
self,
chunk_size: Optional[int] = None,
chunk_number: Optional[int] = None,
chunk_period: Optional[str] = None,
chunker: Optional[Chunker] = None,
timestamp_column_name: Optional[str] = None,
):
"""Creates a new instance of an abstract DriftCalculator.
Parameters
----------
chunk_size: int
Splits the data into chunks containing `chunks_size` observations.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunk_number: int
Splits the data into `chunk_number` pieces.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunk_period: str
Splits the data according to the given period.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunker: Chunker
The `Chunker` used to split the data sets into a lists of chunks.
timestamp_column_name: str
The column name of the column containing timestamp information.
"""
self.chunker = ChunkerFactory.get_chunker(
chunk_size, chunk_number, chunk_period, chunker, timestamp_column_name
)
self.timestamp_column_name = timestamp_column_name
self.result: Optional[Result] = None
@property
def _logger(self) -> logging.Logger:
return logging.getLogger(__name__)
def fit(self, reference_data: pd.DataFrame, *args, **kwargs) -> Self:
"""Trains the calculator using reference data."""
try:
self._logger.debug(f"fitting {str(self)}")
return self._fit(reference_data, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise CalculatorException(f"failed while fitting {str(self)}.\n{exc}")
def calculate(self, data: pd.DataFrame, *args, **kwargs) -> Result:
"""Performs a calculation on the provided data."""
try:
self._logger.debug(f"calculating {str(self)}")
return self._calculate(data, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise CalculatorException(f"failed while calculating {str(self)}.\n{exc}")
@abstractmethod
def _fit(self, reference_data: pd.DataFrame, *args, **kwargs) -> Self:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the '_fit' method")
@abstractmethod
def _calculate(self, data: pd.DataFrame, *args, **kwargs) -> Result:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the '_calculate' method")
class AbstractEstimatorResult(ABC):
"""Contains the results of a drift calculation and provides additional functionality such as plotting.
The result of the :meth:`~nannyml.drift.base.DriftCalculator.calculate` method of a
:class:`~nannyml.drift.base.DriftCalculator`.
It is an abstract class containing shared properties and methods across implementations.
For each :class:`~nannyml.drift.base.DriftCalculator` class there will be an associated
:class:`~nannyml.drift.base.DriftResult` implementation.
"""
DEFAULT_COLUMNS = ['key', 'chunk_index', 'start_index', 'end_index', 'start_date', 'end_date', 'period']
def __init__(self, results_data: pd.DataFrame):
"""Creates a new DriftResult instance.
Parameters
----------
results_data: pd.DataFrame
The result data of the performed calculation.
"""
self.data = results_data.copy(deep=True)
@property
def _logger(self) -> logging.Logger:
return logging.getLogger(__name__)
@property
def empty(self) -> bool:
return self.data is None or self.data.empty
def to_df(self, multilevel: bool = True):
"""Export results do pandas dataframe."""
if multilevel:
return self.data
else:
column_names = [
'_'.join(col).replace('chunk_chunk_chunk', 'chunk').replace('chunk_chunk', 'chunk')
for col in self.data.columns.values
]
single_level_data = self.data.copy(deep=True)
single_level_data.columns = column_names
return single_level_data
def filter(self, period: str = 'all', metrics: Optional[Union[str, List[str]]] = None, *args, **kwargs) -> Self:
"""Returns result metric data."""
if metrics and not isinstance(metrics, (str, list)):
raise InvalidArgumentsException("metrics value provided is not a valid metric or list of metrics")
if isinstance(metrics, str):
metrics = [metrics]
try:
return self._filter(period, metrics, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise EstimatorException(f"could not read result data: {exc}")
@abstractmethod
def _filter(self, period: str, metrics: Optional[List[str]] = None, *args, **kwargs) -> Self:
raise NotImplementedError
def plot(self, *args, **kwargs) -> plotly.graph_objects.Figure:
"""Plot drift results."""
raise NotImplementedError
class AbstractEstimator(ABC):
"""Base class for drift calculation."""
def __init__(
self,
chunk_size: Optional[int] = None,
chunk_number: Optional[int] = None,
chunk_period: Optional[str] = None,
chunker: Optional[Chunker] = None,
timestamp_column_name: Optional[str] = None,
):
"""Creates a new instance of an abstract DriftCalculator.
Parameters
----------
chunk_size: int
Splits the data into chunks containing `chunks_size` observations.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunk_number: int
Splits the data into `chunk_number` pieces.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunk_period: str
Splits the data according to the given period.
Only one of `chunk_size`, `chunk_number` or `chunk_period` should be given.
chunker : Chunker
The `Chunker` used to split the data sets into a lists of chunks.
timestamp_column_name: str
The column name of the column containing timestamp information.
"""
self.chunker = ChunkerFactory.get_chunker(
chunk_size, chunk_number, chunk_period, chunker, timestamp_column_name
)
self.timestamp_column_name = timestamp_column_name
self.result: Optional[Result] = None
@property
def _logger(self) -> logging.Logger:
return logging.getLogger(__name__)
def __str__(self):
return f'{self.__module__}.{self.__class__.__name__}'
def fit(self, reference_data: pd.DataFrame, *args, **kwargs) -> Self:
"""Trains the calculator using reference data."""
try:
self._logger.info(f"fitting {str(self)}")
return self._fit(reference_data, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise CalculatorException(f"failed while fitting {str(self)}.\n{exc}")
def estimate(self, data: pd.DataFrame, *args, **kwargs) -> Result:
"""Performs a calculation on the provided data."""
try:
self._logger.info(f"estimating {str(self)}")
return self._estimate(data, *args, **kwargs)
except NannyMLException:
raise
except Exception as exc:
raise CalculatorException(f"failed while calculating {str(self)}.\n{exc}")
@abstractmethod
def _fit(self, reference_data: pd.DataFrame, *args, **kwargs) -> Self:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the '_fit' method")
@abstractmethod
def _estimate(self, data: pd.DataFrame, *args, **kwargs) -> Result:
raise NotImplementedError(f"'{self.__class__.__name__}' must implement the '_calculate' method")
def _split_features_by_type(data: pd.DataFrame, feature_column_names: List[str]) -> Tuple[List[str], List[str]]:
continuous_column_names = [col for col in feature_column_names if _column_is_continuous(data[col])]
categorical_column_names = [col for col in feature_column_names if _column_is_categorical(data[col])]
return continuous_column_names, categorical_column_names
def _column_is_categorical(column: pd.Series) -> bool:
return column.dtype in ['object', 'string', 'category', 'bool']
@overload
def _remove_nans(data: pd.Series) -> pd.Series:
...
@overload
def _remove_nans(data: pd.DataFrame, columns: Optional[Iterable[Union[str, Iterable[str]]]]) -> pd.DataFrame:
...
def _remove_nans(
data: Union[pd.Series, pd.DataFrame], columns: Optional[Iterable[Union[str, Iterable[str]]]] = None
) -> Tuple[pd.DataFrame, ...]:
"""Remove rows with NaN values in the specified columns.
If no columns are given, drop rows with NaN values in any column. If columns are given, drop rows with NaN values
in the specified columns. If a set of columns is given, drop rows with NaN values in all of the columns in the set.
"""
# If no columns are given, drop rows with NaN values in any columns
if columns is None:
mask = ~data.isna()
if isinstance(mask, pd.DataFrame):
mask = mask.all(axis=1)
else:
mask = np.ones(len(data), dtype=bool)
for column_selector in columns:
nans = data[column_selector].isna()
if isinstance(nans, pd.DataFrame):
nans = nans.all(axis=1)
mask &= ~nans
# NaN values have been dropped. Try to infer types again
return data[mask].reset_index(drop=True).infer_objects()
def _column_is_continuous(column: pd.Series) -> bool:
return column.dtype in [
'int_',
'int8',
'int16',
'int32',
'int64',
'uint8',
'uint16',
'uint32',
'uint64',
'float_',
'float16',
'float32',
'float64',
]
def _list_missing(columns_to_find: List, dataset_columns: Union[List, pd.DataFrame]):
if isinstance(dataset_columns, pd.DataFrame):
dataset_columns = dataset_columns.columns
missing = [col for col in columns_to_find if col not in dataset_columns]
if missing:
raise InvalidArgumentsException(f"missing required columns '{missing}' in data set:\n\t{dataset_columns}")
def _raise_exception_for_negative_values(column: pd.Series):
"""Raises an InvalidArgumentsException if a given column contains negative values.
Parameters
----------
column: pd.Series
Column to check for negative values.
Raises
------
nannyml.exceptions.InvalidArgumentsException
"""
if any(column.values < 0):
negative_item_indices = np.where(column.values < 0)
raise InvalidArgumentsException(
f"target values '{column.name}' contain negative values.\n"
"\tLog-based metrics are not supported for negative target values.\n"
f"\tCheck '{column.name}' at rows {str(negative_item_indices)}."
)
def _common_nan_removal_dataframe(data: pd.DataFrame, selected_columns: List[str]) -> Tuple[pd.DataFrame, bool]:
"""
Remove rows of dataframe containing NaN values on selected columns.
Parameters
----------
data: pd.DataFrame
Pandas dataframe containing data.
selected_columns: List[str]
List containing the strings of column names
Returns
-------
df:
Dataframe with rows containing NaN's on selected_columns removed. All columns of original
dataframe are being returned.
empty:
Boolean whether the resulting data are contain any rows (false) or not (true)
"""
if not set(selected_columns) <= set(data.columns):
raise InvalidArgumentsException(
f"Selected columns: {selected_columns} not all present in provided data columns {list(data.columns)}"
)
df = data.dropna(axis=0, how='any', inplace=False, subset=selected_columns).reset_index(drop=True).infer_objects()
empty: bool = df.shape[0] == 0
return df, empty
def _common_nan_removal_ndarrays(data: Sequence[np.array], selected_columns: List[int]) -> Tuple[pd.DataFrame, bool]:
"""
Remove rows of numpy arrays containing NaN values on selected columns.
Parameters
----------
data: Sequence[np.array]
Sequence containing numpy arrays.
selected_columns: List[int]
List containing the indices of column numbers
Returns
-------
df:
Dataframe with rows containing NaN's on selected_columns removed. The columns of the DataFrame are the
numpy ndarrays in the same order as the input data.
empty:
Boolean whether the resulting data are contain any rows (false) or not (true)
"""
# Check if all selected_columns indices are valid for the first ndarray
if not all(col < len(data) for col in selected_columns):
raise InvalidArgumentsException(
f"Selected columns: {selected_columns} not all present in provided data columns with shape {data[0].shape}"
)
# Convert the numpy ndarrays to a pandas dataframe
df = pd.DataFrame({f'col_{i}': col for i, col in enumerate(data)})
# Use the dataframe function to remove NaNs
selected_columns_names = [df.columns[col] for col in selected_columns]
result, empty = _common_nan_removal_dataframe(df, selected_columns_names)
return result, empty
@overload
def common_nan_removal(data: pd.DataFrame, selected_columns: List[str]) -> Tuple[pd.DataFrame, bool]:
...
@overload
def common_nan_removal(data: Sequence[np.array], selected_columns: List[int]) -> Tuple[pd.DataFrame, bool]:
...
def common_nan_removal(
data: Union[pd.DataFrame, Sequence[np.array]], selected_columns: Union[List[str], List[int]]
) -> Tuple[pd.DataFrame, bool]:
"""
Wrapper function to handle both pandas DataFrame and sequences of numpy ndarrays.
Parameters
----------
data: Union[pd.DataFrame, Sequence[np.array]]
Pandas dataframe or sequence of numpy ndarrays containing data.
selected_columns: Union[List[str], List[int]]
List containing the column names or indices
Returns
-------
result:
Dataframe with rows containing NaN's on selected columns removed. All columns of original
dataframe or ndarrays are being returned.
empty:
Boolean whether the resulting data contains any rows (false) or not (true)
"""
if isinstance(data, pd.DataFrame):
if not all(isinstance(col, str) for col in selected_columns):
raise TypeError("When data is a pandas DataFrame, selected_columns should be a list of strings.")
return _common_nan_removal_dataframe(data, selected_columns) # type: ignore
elif isinstance(data, Sequence) and all(isinstance(arr, np.ndarray) for arr in data):
if not all(isinstance(col, int) for col in selected_columns):
raise TypeError("When data is a sequence of numpy ndarrays, selected_columns should be a list of integers.")
return _common_nan_removal_ndarrays(data, selected_columns) # type: ignore
else:
raise TypeError("Data should be either a pandas DataFrame or a sequence of numpy ndarrays.")