Repository: feature-engine/feature_engine
Pull request #716 (2023-12-27 18:12:06)

refactor find_all_variables

codecov[bot]: ## [Codecov](https://app.codecov.io/gh/feature-engine/feature_engine/pull/716?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feature-engine) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Comparison is base [(`4f430d1`)](https://app.codecov.io/gh/feature-engine/feature_engine/commit/4f430d11aae7e07c273d20b9f03749b00103fd1c?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feature-engine) 98.06% compared to head [(`7dad1bf`)](https://app.codecov.io/gh/feature-engine/feature_engine/pull/716?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feature-engine) 98.17%.


<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main     #716      +/-   ##
==========================================
+ Coverage   98.06%   98.17%   +0.11%     
==========================================
  Files         102      102              
  Lines        3927     3946      +19     
  Branches      772      780       +8     
==========================================
+ Hits         3851     3874      +23     
+ Misses         28       26       -2     
+ Partials       48       46       -2     
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/feature-engine/feature_engine/pull/716?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feature-engine).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=feature-engine).


Patch:
diff --git a/docs/api_doc/variable_handling/check_all_variables.rst b/docs/api_doc/variable_handling/check_all_variables.rst
new file mode 100644
index 0000000..0cfa42e
--- /dev/null
+++ b/docs/api_doc/variable_handling/check_all_variables.rst
@@ -0,0 +1,6 @@
+check_all_variables
+===================
+
+.. currentmodule:: feature_engine.variable_handling
+
+.. autofunction:: check_all_variables
\ No newline at end of file
diff --git a/docs/api_doc/variable_handling/index.rst b/docs/api_doc/variable_handling/index.rst
index b8297e1..05ac0f7 100644
--- a/docs/api_doc/variable_handling/index.rst
+++ b/docs/api_doc/variable_handling/index.rst
@@ -22,6 +22,7 @@ variables that they will modify.
    find_datetime_variables
    find_numerical_variables
    find_categorical_and_numerical_variables
+   check_all_variables
    check_categorical_variables
    check_datetime_variables
    check_numerical_variables
diff --git a/docs/user_guide/variable_handling/check_all_variables.rst b/docs/user_guide/variable_handling/check_all_variables.rst
new file mode 100644
index 0000000..b53aea7
--- /dev/null
+++ b/docs/user_guide/variable_handling/check_all_variables.rst
@@ -0,0 +1,88 @@
+.. _check_all_vars:
+
+.. currentmodule:: feature_engine.variable_handling
+
+check_all_variables
+===================
+
+With :class:`check_all_variables()` we can check that the variables in a list are
+present in the dataframe.
+
+Let's create a toy dataset with numerical, categorical and datetime variables:
+
+.. code:: python
+
+    import pandas as pd
+    from sklearn.datasets import make_classification
+
+    X, y = make_classification(
+        n_samples=1000,
+        n_features=4,
+        n_redundant=1,
+        n_clusters_per_class=1,
+        weights=[0.50],
+        class_sep=2,
+        random_state=1,
+    )
+
+    # transform arrays into pandas df and series
+    colnames = [f"num_var_{i+1}" for i in range(4)]
+    X = pd.DataFrame(X, columns=colnames)
+
+    X["cat_var1"] = ["Hello"] * 1000
+    X["cat_var2"] = ["Bye"] * 1000
+
+    X["date1"] = pd.date_range("2020-02-24", periods=1000, freq="T")
+    X["date2"] = pd.date_range("2021-09-29", periods=1000, freq="H")
+    X["date3"] = ["2020-02-24"] * 1000
+
+    print(X.head())
+
+We see the resulting dataframe below:
+
+.. code:: python
+
+       num_var_1  num_var_2  num_var_3  num_var_4 cat_var1 cat_var2  \
+    0  -1.558594   1.634123   1.556932   2.869318    Hello      Bye
+    1   1.499925   1.651008   1.159977   2.510196    Hello      Bye
+    2   0.277127  -0.263527   0.532159   0.274491    Hello      Bye
+    3  -1.139190  -1.131193   2.296540   1.189781    Hello      Bye
+    4  -0.530061  -2.280109   2.469580   0.365617    Hello      Bye
+
+                    date1               date2       date3
+    0 2020-02-24 00:00:00 2021-09-29 00:00:00  2020-02-24
+    1 2020-02-24 00:01:00 2021-09-29 01:00:00  2020-02-24
+    2 2020-02-24 00:02:00 2021-09-29 02:00:00  2020-02-24
+    3 2020-02-24 00:03:00 2021-09-29 03:00:00  2020-02-24
+    4 2020-02-24 00:04:00 2021-09-29 04:00:00  2020-02-24
+
+
+We can use :class:`check_all_variables()` with a list of variable names to verify that
+the variables in the list are in the dataframe.
+
+.. code:: python
+
+    from feature_engine.variable_handling import check_all_variables
+
+    checked_vars = check_all_variables(X, ["num_var_1", "cat_var1", "date1"])
+
+    checked_vars
+
+The output is the list of variable names passed to the function:
+
+.. code:: python
+
+    ['num_var_1', 'cat_var1', 'date1']
+
+If we pass the name of a variable that is not in the dataframe, :class:`check_all_variables()`
+will return an error:
+
+.. code:: python
+
+    check_all_variables(X, ["hola", "cat_var1", "date1"])
+
+Below we see the error message:
+
+.. code:: python
+
+    KeyError: 'Some of the variables are not in the dataframe.'
\ No newline at end of file
diff --git a/docs/user_guide/variable_handling/check_categorical_variables.rst b/docs/user_guide/variable_handling/check_categorical_variables.rst
index ccdf7cb..8fc6f6b 100644
--- a/docs/user_guide/variable_handling/check_categorical_variables.rst
+++ b/docs/user_guide/variable_handling/check_categorical_variables.rst
@@ -1,6 +1,6 @@
 .. _check_cat_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 check_categorical_variables
 ===========================
diff --git a/docs/user_guide/variable_handling/check_datetime_variables.rst b/docs/user_guide/variable_handling/check_datetime_variables.rst
index 2302b33..8b1f572 100644
--- a/docs/user_guide/variable_handling/check_datetime_variables.rst
+++ b/docs/user_guide/variable_handling/check_datetime_variables.rst
@@ -1,6 +1,6 @@
 .. _check_datetime_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 check_datetime_variables
 ========================
diff --git a/docs/user_guide/variable_handling/check_numerical_variables.rst b/docs/user_guide/variable_handling/check_numerical_variables.rst
index 297c33a..3212be2 100644
--- a/docs/user_guide/variable_handling/check_numerical_variables.rst
+++ b/docs/user_guide/variable_handling/check_numerical_variables.rst
@@ -1,6 +1,6 @@
 .. _check_num_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 check_numerical_variables
 =========================
diff --git a/docs/user_guide/variable_handling/find_all_variables.rst b/docs/user_guide/variable_handling/find_all_variables.rst
index eac33d4..677dcb8 100644
--- a/docs/user_guide/variable_handling/find_all_variables.rst
+++ b/docs/user_guide/variable_handling/find_all_variables.rst
@@ -1,6 +1,6 @@
 ﻿.. _find_all_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 find_all_variables
 ==================
@@ -102,32 +102,3 @@ In the list below, we can see that variables of type datetime were ignored:
      'cat_var1',
      'cat_var2',
      'date3']
-
-
-We can also use :class:`find_all_variables()` with a list of variable names. It will
-corroborate that the variables indicated in the list are in the dataframe.
-
-.. code:: python
-
-    vars_all = find_all_variables(X, ["num_var_1", "cat_var1", "date1"])
-
-    vars_all
-
-The output is the list of variable names passed to the function:
-
-.. code:: python
-
-    ['num_var_1', 'cat_var1', 'date1']
-
-If we pass the name of a variable that is not in the dataframe, :class:`find_all_variables()`
-will return an error:
-
-.. code:: python
-
-    find_all_variables(X, ["hola", "cat_var1", "date1"])
-
-Below we see the error message:
-
-.. code:: python
-
-    KeyError: 'Some of the variables are not in the dataframe.'
\ No newline at end of file
diff --git a/docs/user_guide/variable_handling/find_categorical_and_numerical_variables.rst b/docs/user_guide/variable_handling/find_categorical_and_numerical_variables.rst
index f485173..4366985 100644
--- a/docs/user_guide/variable_handling/find_categorical_and_numerical_variables.rst
+++ b/docs/user_guide/variable_handling/find_categorical_and_numerical_variables.rst
@@ -1,6 +1,6 @@
 ﻿.. _find_cat_and_num_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 find_categorical_and_numerical_variables
 ========================================
diff --git a/docs/user_guide/variable_handling/find_categorical_variables.rst b/docs/user_guide/variable_handling/find_categorical_variables.rst
index 8febc7e..4678016 100644
--- a/docs/user_guide/variable_handling/find_categorical_variables.rst
+++ b/docs/user_guide/variable_handling/find_categorical_variables.rst
@@ -1,6 +1,6 @@
 ﻿.. _find_cat_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 find_categorical_variables
 ==========================
diff --git a/docs/user_guide/variable_handling/find_datetime_variables.rst b/docs/user_guide/variable_handling/find_datetime_variables.rst
index f657928..60bf3d0 100644
--- a/docs/user_guide/variable_handling/find_datetime_variables.rst
+++ b/docs/user_guide/variable_handling/find_datetime_variables.rst
@@ -1,6 +1,6 @@
 ﻿.. _find_datetime_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 find_datetime_variables
 =======================
diff --git a/docs/user_guide/variable_handling/find_numerical_variables.rst b/docs/user_guide/variable_handling/find_numerical_variables.rst
index e6c71fb..ba79d8e 100644
--- a/docs/user_guide/variable_handling/find_numerical_variables.rst
+++ b/docs/user_guide/variable_handling/find_numerical_variables.rst
@@ -1,6 +1,6 @@
 ﻿.. _find_num_vars:
 
-.. currentmodule:: feature_engine.variable_handling.variable_type_selection
+.. currentmodule:: feature_engine.variable_handling
 
 find_numerical_variables
 ========================
diff --git a/docs/user_guide/variable_handling/index.rst b/docs/user_guide/variable_handling/index.rst
index 1f9fc74..e7a5d20 100644
--- a/docs/user_guide/variable_handling/index.rst
+++ b/docs/user_guide/variable_handling/index.rst
@@ -24,6 +24,7 @@ Feature-engine or Scikit-learn compatible transformers.
    find_datetime_variables
    find_numerical_variables
    find_categorical_and_numerical_variables
+   check_all_variables
    check_categorical_variables
    check_datetime_variables
    check_numerical_variables
diff --git a/feature_engine/encoding/base_encoder.py b/feature_engine/encoding/base_encoder.py
index 993a057..0c98068 100644
--- a/feature_engine/encoding/base_encoder.py
+++ b/feature_engine/encoding/base_encoder.py
@@ -22,6 +22,7 @@ from feature_engine.dataframe_checks import (
 )
 from feature_engine.tags import _return_tags
 from feature_engine.variable_handling import (
+    check_all_variables,
     check_categorical_variables,
     find_all_variables,
     find_categorical_variables,
@@ -133,7 +134,10 @@ class CategoricalMethodsMixin(BaseEstimator, TransformerMixin, GetFeatureNamesOu
         """
         # select variables to encode
         if self.ignore_format is True:
-            variables_ = find_all_variables(X, self.variables)
+            if self.variables is None:
+                variables_ = find_all_variables(X)
+            else:
+                variables_ = check_all_variables(X, self.variables)
         else:
             if self.variables is None:
                 variables_ = find_categorical_variables(X)
diff --git a/feature_engine/imputation/categorical.py b/feature_engine/imputation/categorical.py
index 8a12ac6..d0300f7 100644
--- a/feature_engine/imputation/categorical.py
+++ b/feature_engine/imputation/categorical.py
@@ -23,6 +23,7 @@ from feature_engine.dataframe_checks import check_X
 from feature_engine.imputation.base_imputer import BaseImputer
 from feature_engine.tags import _return_tags
 from feature_engine.variable_handling import (
+    check_all_variables,
     check_categorical_variables,
     find_all_variables,
     find_categorical_variables,
@@ -167,7 +168,10 @@ class CategoricalImputer(BaseImputer):
 
         # select variables to encode
         if self.ignore_format is True:
-            self.variables_ = find_all_variables(X, self.variables)
+            if self.variables is None:
+                self.variables_ = find_all_variables(X)
+            else:
+                self.variables_ = check_all_variables(X, self.variables)
         else:
             if self.variables is None:
                 self.variables_ = find_categorical_variables(X)
diff --git a/feature_engine/imputation/drop_missing_data.py b/feature_engine/imputation/drop_missing_data.py
index 23ea299..5fb211f 100644
--- a/feature_engine/imputation/drop_missing_data.py
+++ b/feature_engine/imputation/drop_missing_data.py
@@ -17,7 +17,7 @@ from feature_engine._docstrings.substitute import Substitution
 from feature_engine.dataframe_checks import check_X
 from feature_engine.imputation.base_imputer import BaseImputer
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 
 @Substitution(
@@ -144,7 +144,10 @@ class DropMissingData(BaseImputer):
         X = check_X(X)
 
         # find variables for which indicator should be added
-        self.variables_ = find_all_variables(X, self.variables)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X)
+        else:
+            self.variables_ = check_all_variables(X, self.variables)
 
         # If user passes a threshold, then missing_only is ignored:
         if self.threshold is None and self.missing_only is True:
diff --git a/feature_engine/imputation/missing_indicator.py b/feature_engine/imputation/missing_indicator.py
index 10f70e2..9e827f0 100644
--- a/feature_engine/imputation/missing_indicator.py
+++ b/feature_engine/imputation/missing_indicator.py
@@ -17,7 +17,7 @@ from feature_engine._docstrings.substitute import Substitution
 from feature_engine.dataframe_checks import check_X
 from feature_engine.imputation.base_imputer import BaseImputer
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 
 @Substitution(
@@ -128,7 +128,10 @@ class AddMissingIndicator(BaseImputer):
         X = check_X(X)
 
         # find variables for which indicator should be added
-        self.variables_ = find_all_variables(X, self.variables)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X)
+        else:
+            self.variables_ = check_all_variables(X, self.variables)
 
         if self.missing_only is True:
             self.variables_ = [
diff --git a/feature_engine/imputation/random_sample.py b/feature_engine/imputation/random_sample.py
index 7ae1c6f..bac6616 100644
--- a/feature_engine/imputation/random_sample.py
+++ b/feature_engine/imputation/random_sample.py
@@ -22,7 +22,7 @@ from feature_engine._docstrings.substitute import Substitution
 from feature_engine.dataframe_checks import check_X
 from feature_engine.imputation.base_imputer import BaseImputer
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 
 # for RandomSampleImputer
@@ -183,7 +183,10 @@ class RandomSampleImputer(BaseImputer):
         X = check_X(X)
 
         # find variables to impute
-        self.variables_ = find_all_variables(X, self.variables)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X)
+        else:
+            self.variables_ = check_all_variables(X, self.variables)
 
         # take a copy of the selected variables
         self.X_ = X[self.variables_].copy()
diff --git a/feature_engine/selection/drop_constant_features.py b/feature_engine/selection/drop_constant_features.py
index 8de3315..c179485 100644
--- a/feature_engine/selection/drop_constant_features.py
+++ b/feature_engine/selection/drop_constant_features.py
@@ -22,7 +22,7 @@ from feature_engine._docstrings.substitute import Substitution
 from feature_engine.dataframe_checks import _check_contains_na, check_X
 from feature_engine.selection.base_selector import BaseSelector
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 Variables = Union[None, int, str, List[Union[str, int]]]
 
@@ -178,7 +178,10 @@ class DropConstantFeatures(BaseSelector):
         self._confirm_variables(X)
 
         # find all variables or check those entered are present in the dataframe
-        self.variables_ = find_all_variables(X, self.variables_)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X)
+        else:
+            self.variables_ = check_all_variables(X, self.variables_)
 
         if self.missing_values == "raise":
             # check if dataset contains na
diff --git a/feature_engine/selection/drop_duplicate_features.py b/feature_engine/selection/drop_duplicate_features.py
index 255f000..ac9be20 100644
--- a/feature_engine/selection/drop_duplicate_features.py
+++ b/feature_engine/selection/drop_duplicate_features.py
@@ -24,7 +24,7 @@ from feature_engine._docstrings.substitute import Substitution
 from feature_engine.dataframe_checks import _check_contains_na, check_X
 from feature_engine.selection.base_selector import BaseSelector
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 Variables = Union[None, int, str, List[Union[str, int]]]
 
@@ -140,7 +140,10 @@ class DropDuplicateFeatures(BaseSelector):
         self._confirm_variables(X)
 
         # find all variables or check those entered are in the dataframe
-        self.variables_ = find_all_variables(X, self.variables_)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X)
+        else:
+            self.variables_ = check_all_variables(X, self.variables_)
 
         # check that there are more than 1 variable to select from
         self._check_variable_number()
diff --git a/feature_engine/selection/drop_features.py b/feature_engine/selection/drop_features.py
index cce5fa8..3420ee0 100644
--- a/feature_engine/selection/drop_features.py
+++ b/feature_engine/selection/drop_features.py
@@ -5,7 +5,7 @@ import pandas as pd
 from feature_engine.dataframe_checks import check_X
 from feature_engine.selection.base_selector import BaseSelector
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables
 
 
 class DropFeatures(BaseSelector):
@@ -93,11 +93,7 @@ class DropFeatures(BaseSelector):
         # check input dataframe
         X = check_X(X)
 
-        # X[self.features_to_drops] calls to pandas to check if columns are
-        # present in the df.
-        X[self.features_to_drop]
-
-        self.features_to_drop_ = find_all_variables(X, variables=self.features_to_drop)
+        self.features_to_drop_ = check_all_variables(X, variables=self.features_to_drop)
 
         # check user is not removing all columns in the dataframe
         if len(self.features_to_drop_) == len(X.columns):
diff --git a/feature_engine/selection/information_value.py b/feature_engine/selection/information_value.py
index 3aaf37b..0ec7fd9 100644
--- a/feature_engine/selection/information_value.py
+++ b/feature_engine/selection/information_value.py
@@ -30,7 +30,8 @@ from feature_engine.discretisation import (
 from feature_engine.encoding.woe import WoE
 from feature_engine.selection.base_selector import BaseSelector
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import (
+from feature_engine.variable_handling import (
+    check_all_variables,
     find_all_variables,
     find_categorical_and_numerical_variables,
 )
@@ -212,7 +213,10 @@ class SelectByInformationValue(BaseSelector, WoE):
 
         # find categorical and numerical variables
         # find all variables or check those entered are present in the dataframe
-        self.variables_ = find_all_variables(X, self.variables_, exclude_datetime=True)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X, exclude_datetime=True)
+        else:
+            self.variables_ = check_all_variables(X, self.variables_)
 
         _, variables_numerical = find_categorical_and_numerical_variables(
             X, self.variables_
diff --git a/feature_engine/selection/target_mean_selection.py b/feature_engine/selection/target_mean_selection.py
index d58c74a..b5c98fe 100644
--- a/feature_engine/selection/target_mean_selection.py
+++ b/feature_engine/selection/target_mean_selection.py
@@ -35,7 +35,7 @@ from feature_engine.selection._selection_constants import (
 )
 from feature_engine.selection.base_selector import BaseSelector
 from feature_engine.tags import _return_tags
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling import check_all_variables, find_all_variables
 
 Variables = Union[None, int, str, List[Union[str, int]]]
 
@@ -272,7 +272,10 @@ class SelectByTargetMeanPerformance(BaseSelector):
         self._confirm_variables(X)
 
         # find all variables or check those entered are present in the dataframe
-        self.variables_ = find_all_variables(X, self.variables_, exclude_datetime=True)
+        if self.variables is None:
+            self.variables_ = find_all_variables(X, exclude_datetime=True)
+        else:
+            self.variables_ = check_all_variables(X, self.variables_)
 
         if len(self.variables_) == 1 and self.threshold is None:
             raise ValueError(
diff --git a/feature_engine/variable_handling/__init__.py b/feature_engine/variable_handling/__init__.py
index d49303c..8267295 100644
--- a/feature_engine/variable_handling/__init__.py
+++ b/feature_engine/variable_handling/__init__.py
@@ -4,26 +4,26 @@ or check that a list of variables is in certain type.
 """
 
 from .check_variables import (
+    check_all_variables,
     check_categorical_variables,
     check_datetime_variables,
     check_numerical_variables,
 )
 from .find_variables import (
+    find_all_variables,
     find_categorical_variables,
     find_datetime_variables,
     find_numerical_variables,
 )
-from .variable_selection import (
-    find_all_variables,
-    find_categorical_and_numerical_variables,
-)
+from .variable_selection import find_categorical_and_numerical_variables
 
 __all__ = [
-    "find_all_variables",
     "find_categorical_and_numerical_variables",
+    "check_all_variables",
     "check_numerical_variables",
     "check_categorical_variables",
     "check_datetime_variables",
+    "find_all_variables",
     "find_numerical_variables",
     "find_categorical_variables",
     "find_datetime_variables",
diff --git a/feature_engine/variable_handling/check_variables.py b/feature_engine/variable_handling/check_variables.py
index 155a4a5..1a43506 100644
--- a/feature_engine/variable_handling/check_variables.py
+++ b/feature_engine/variable_handling/check_variables.py
@@ -105,7 +105,8 @@ def check_categorical_variables(
 
 
 def check_datetime_variables(
-    X: pd.DataFrame, variables: Variables,
+    X: pd.DataFrame,
+    variables: Variables,
 ) -> List[Union[str, int]]:
     """
     Checks that the variables in the list are or can be parsed as datetime.
@@ -154,3 +155,52 @@ def check_datetime_variables(
         )
 
     return variables
+
+
+def check_all_variables(
+    X: pd.DataFrame,
+    variables: Variables,
+) -> List[Union[str, int]]:
+    """
+    Checks that the variables in the list are in the dataframe.
+
+    More details in the :ref:`User Guide <check_all_vars>`.
+
+    Parameters
+    ----------
+    X : pandas dataframe of shape = [n_samples, n_features]
+        The dataset
+
+    variables : list
+        The list with the names of the variables to check.
+
+    Returns
+    -------
+    variables: List
+        The names of the variables.
+
+    Examples
+    --------
+    >>> import pandas as pd
+    >>> from feature_engine.variable_handling import check_all_variables
+    >>> X = pd.DataFrame({
+    >>>     "var_num": [1, 2, 3],
+    >>>     "var_cat": ["A", "B", "C"],
+    >>>     "var_date": pd.date_range("2020-02-24", periods=3, freq="T")
+    >>> })
+    >>> vars_all = check_all_variables(X, ['var_num', 'var_cat', 'var_date'])
+    >>> vars_all
+    ['var_num', 'var_cat', 'var_date']
+    """
+    if isinstance(variables, (str, int)):
+        if variables not in X.columns.to_list():
+            raise KeyError(f"The variable {variables} is not in the dataframe.")
+        variables_ = [variables]
+
+    else:
+        if not set(variables).issubset(set(X.columns)):
+            raise KeyError("Some of the variables are not in the dataframe.")
+
+        variables_ = variables
+
+    return variables_
diff --git a/feature_engine/variable_handling/find_variables.py b/feature_engine/variable_handling/find_variables.py
index c732a38..4d140f5 100644
--- a/feature_engine/variable_handling/find_variables.py
+++ b/feature_engine/variable_handling/find_variables.py
@@ -135,3 +135,46 @@ def find_datetime_variables(X: pd.DataFrame) -> List[Union[str, int]]:
         raise ValueError("No datetime variables found in this dataframe.")
 
     return variables
+
+
+def find_all_variables(
+    X: pd.DataFrame,
+    exclude_datetime: bool = False,
+) -> List[Union[str, int]]:
+    """
+    Returns a list with the names of all the variables in the dataframe. It has the
+    option to exlcude variables that can be parsed as datetime.
+
+    More details in the :ref:`User Guide <find_all_vars>`.
+
+    Parameters
+    ----------
+    X : pandas dataframe of shape = [n_samples, n_features]
+        The dataset
+
+    exclude_datetime: bool, default=False
+        Whether to exclude datetime variables.
+
+    Returns
+    -------
+    variables: List
+        The names of the variables.
+
+    Examples
+    --------
+    >>> import pandas as pd
+    >>> from feature_engine.variable_handling import find_all_variables
+    >>> X = pd.DataFrame({
+    >>>     "var_num": [1, 2, 3],
+    >>>     "var_cat": ["A", "B", "C"],
+    >>>     "var_date": pd.date_range("2020-02-24", periods=3, freq="T")
+    >>> })
+    >>> vars_all = find_all_variables(X)
+    >>> vars_all
+    ['var_num', 'var_cat', 'var_date']
+    """
+    if exclude_datetime is True:
+        variables = X.select_dtypes(exclude="datetime").columns.to_list()
+    else:
+        variables = X.columns.to_list()
+    return variables
diff --git a/feature_engine/variable_handling/variable_selection.py b/feature_engine/variable_handling/variable_selection.py
index 85cdfbe..afcf26d 100644
--- a/feature_engine/variable_handling/variable_selection.py
+++ b/feature_engine/variable_handling/variable_selection.py
@@ -13,72 +13,6 @@ from feature_engine.variable_handling._variable_type_checks import (
 Variables = Union[None, int, str, List[Union[str, int]]]
 
 
-def find_all_variables(
-    X: pd.DataFrame,
-    variables: Variables = None,
-    exclude_datetime: bool = False,
-) -> List[Union[str, int]]:
-    """
-    Returns the names of all the variables in the dataframe in a list. Alternatively,
-    it will check that the variables indicated by the user are in the dataframe.
-
-    More details in the :ref:`User Guide <find_all_vars>`.
-
-    Parameters
-    ----------
-    X : pandas dataframe of shape = [n_samples, n_features]
-        The dataset
-
-    variables : list, default=None
-        If `None`, the function will return the names of all the variables in X.
-        Alternatively, it checks that the variables in the list are present in the
-        dataframe.
-
-    exclude_datetime: bool, default=False
-        Whether to exclude datetime variables.
-
-    Returns
-    -------
-    variables: List
-        The names of the variables.
-
-    Examples
-    --------
-    >>> import pandas as pd
-    >>> from feature_engine.variable_handling import find_all_variables
-    >>> X = pd.DataFrame({
-    >>>     "var_num": [1, 2, 3],
-    >>>     "var_cat": ["A", "B", "C"],
-    >>>     "var_date": pd.date_range("2020-02-24", periods=3, freq="T")
-    >>> })
-    >>> vars_all = find_all_variables(X)
-    >>> vars_all
-    ['var_num', 'var_cat', 'var_date']
-    """
-    # find all variables in dataset
-    if variables is None:
-        if exclude_datetime is True:
-            variables_ = X.select_dtypes(exclude="datetime").columns.to_list()
-        else:
-            variables_ = X.columns.to_list()
-
-    elif isinstance(variables, (str, int)):
-        if variables not in X.columns.to_list():
-            raise ValueError(f"The variable {variables} is not in the dataframe.")
-        variables_ = [variables]
-
-    else:
-        if len(variables) == 0:
-            raise ValueError("The list of variables is empty.")
-
-        if any(f for f in variables if f not in X.columns):
-            raise KeyError("Some of the variables are not in the dataframe.")
-
-        variables_ = variables
-
-    return variables_
-
-
 def _filter_out_variables_not_in_dataframe(X, variables):
     """Filter out variables that are not present in the dataframe.
 
diff --git a/feature_engine/wrappers/wrappers.py b/feature_engine/wrappers/wrappers.py
index 1fba703..6bee328 100644
--- a/feature_engine/wrappers/wrappers.py
+++ b/feature_engine/wrappers/wrappers.py
@@ -13,7 +13,8 @@ from feature_engine.variable_handling import (
     check_numerical_variables,
     find_numerical_variables,
 )
-from feature_engine.variable_handling.variable_selection import find_all_variables
+from feature_engine.variable_handling.check_variables import check_all_variables
+from feature_engine.variable_handling.find_variables import find_all_variables
 
 _SELECTORS = [
     "GenericUnivariateSelect",
@@ -260,7 +261,10 @@ class SklearnTransformerWrapper(BaseEstimator, TransformerMixin):
             "SimpleImputer",
             "FunctionTransformer",
         ]:
-            self.variables_ = find_all_variables(X, self.variables)
+            if self.variables is None:
+                self.variables_ = find_all_variables(X)
+            else:
+                self.variables_ = check_all_variables(X, self.variables)
 
         else:
             if self.variables is None:


Test patch:
diff --git a/tests/test_variable_handling/test_check_variables.py b/tests/test_variable_handling/test_check_variables.py
index ad892c3..448f3a3 100644
--- a/tests/test_variable_handling/test_check_variables.py
+++ b/tests/test_variable_handling/test_check_variables.py
@@ -1,6 +1,7 @@
 import pytest
 
 from feature_engine.variable_handling import (
+    check_all_variables,
     check_categorical_variables,
     check_datetime_variables,
     check_numerical_variables,
@@ -122,3 +123,41 @@ def test_check_datetime_variables_raises_errors_when_not_datetime(df_datetime):
     with pytest.raises(TypeError):
         assert check_datetime_variables(df_datetime, variables=["date_range", "Age"])
     assert str(record.value) == msg
+
+
+@pytest.mark.parametrize(
+    "input_vars",
+    [
+        ["Name", "City", "Age", "Marks", "dob"],
+        [
+            "Name",
+            "City",
+            "Age",
+            "Marks",
+        ],
+        "Name",
+        ["Age"],
+    ],
+)
+def test_check_all_variables_returns_all_variables(df_vartypes, input_vars):
+    if isinstance(input_vars, list):
+        assert check_all_variables(df_vartypes, input_vars) == input_vars
+    else:
+        assert check_all_variables(df_vartypes, input_vars) == [input_vars]
+
+
+@pytest.mark.parametrize(
+    "input_vars", [["Name", "City", "Absent"], "Absent", ["Absent"]]
+)
+def test_check_all_variables_raises_errors_when_not_in_dataframe(
+    df_vartypes, input_vars
+):
+    msg_ls = "'Some of the variables are not in the dataframe.'"
+    msg_single = "'The variable Absent is not in the dataframe.'"
+
+    with pytest.raises(KeyError) as record:
+        assert check_all_variables(df_vartypes, input_vars)
+    if isinstance(input_vars, list):
+        assert str(record.value) == msg_ls
+    else:
+        assert str(record.value) == msg_single
diff --git a/tests/test_variable_handling/test_find_variables.py b/tests/test_variable_handling/test_find_variables.py
index 6fb81dc..b8b6764 100644
--- a/tests/test_variable_handling/test_find_variables.py
+++ b/tests/test_variable_handling/test_find_variables.py
@@ -1,6 +1,7 @@
 import pytest
 
 from feature_engine.variable_handling import (
+    find_all_variables,
     find_categorical_variables,
     find_datetime_variables,
     find_numerical_variables,
@@ -71,3 +72,11 @@ def test_datetime_variables_raises_error_when_no_datetime_variables(df_datetime)
     with pytest.raises(ValueError) as record:
         assert find_datetime_variables(df_datetime.loc[:, vars_nondt])
     assert str(record.value) == msg
+
+
+def test_find_all_variables(df_vartypes):
+    all_vars = ["Name", "City", "Age", "Marks", "dob"]
+    all_vars_no_dt = ["Name", "City", "Age", "Marks"]
+
+    assert find_all_variables(df_vartypes, exclude_datetime=False) == all_vars
+    assert find_all_variables(df_vartypes, exclude_datetime=True) == all_vars_no_dt
diff --git a/tests/test_variable_handling/test_variable_selection.py b/tests/test_variable_handling/test_variable_selection.py
index aa009c7..274f863 100644
--- a/tests/test_variable_handling/test_variable_selection.py
+++ b/tests/test_variable_handling/test_variable_selection.py
@@ -3,25 +3,9 @@ import pytest
 
 from feature_engine.variable_handling.variable_selection import (
     _filter_out_variables_not_in_dataframe,
-    find_all_variables,
     find_categorical_and_numerical_variables,
 )
 
-
-def test_find_all_variables(df_vartypes):
-    all_vars = ["Name", "City", "Age", "Marks", "dob"]
-    all_vars_no_dt = ["Name", "City", "Age", "Marks"]
-    user_vars = ["Name", "City"]
-    non_existing_vars = ["Grades"]
-
-    assert find_all_variables(df_vartypes) == all_vars
-    assert find_all_variables(df_vartypes, exclude_datetime=True) == all_vars_no_dt
-    assert find_all_variables(df_vartypes, ["Name", "City"]) == user_vars
-
-    with pytest.raises(KeyError):
-        assert find_all_variables(df_vartypes, non_existing_vars)
-
-
 filter_dict = [
     (
         pd.DataFrame(columns=["A", "B", "C", "D", "E"]),