-
Notifications
You must be signed in to change notification settings - Fork 118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Narwhals for dataframe-agnostic codebase #671
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
5e4c04c
placeholder to develop narwhals features
FBruzzesi aac1d9d
feat: make `ColumnDropper` dataframe-agnostic (#655)
MarcoGorelli fe691b5
feat: make ColumnSelector dataframe-agnostic (#659)
anopsy 28c102b
feat: make `add_lags` dataframe-agnostic (#661)
MarcoGorelli 94cf506
Make `RegressionOutlier` dataframe-agnostic (#665)
MarcoGorelli 0773db9
feat: Make InformationFilter dataframe-agnostic
FBruzzesi d09fba5
Make Timegapsplit dataframe-agnostic (#668)
MarcoGorelli 8d33f1c
feat: make FairClassifier data-agnostic (#669)
DeaMariaLeon 7adc625
feat: Make PandasTypeSelector selector dataframe-agnostic (#670)
MarcoGorelli ef74332
format typeselector and bump version
FBruzzesi 96e3ef9
Merge branch 'main' into narwhals-development
FBruzzesi db21a11
Merge branch 'main' into narwhals-development
FBruzzesi 3d1e996
feat: Make grouped and hierarchical dataframe-agnostic (#667)
FBruzzesi 06f24f7
Merge branch 'main' into narwhals-development
FBruzzesi 7f1478c
hacking C
FBruzzesi 009a090
fairness: change C values in tests
FBruzzesi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ on: | |
pull_request: | ||
branches: | ||
- main | ||
- narwhals-development | ||
|
||
jobs: | ||
test: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,55 +1,59 @@ | ||
from typing import Tuple | ||
from __future__ import annotations | ||
|
||
import numpy as np | ||
from typing import List | ||
|
||
import narwhals as nw | ||
import pandas as pd | ||
from scipy.sparse import issparse | ||
from sklearn.utils import check_array | ||
from sklearn.utils.validation import _ensure_no_complex_data | ||
|
||
|
||
def _split_groups_and_values( | ||
X, groups, name="", min_value_cols=1, check_X=True, **kwargs | ||
) -> Tuple[pd.DataFrame, np.ndarray]: | ||
_data_format_checks(X, name=name) | ||
check_array(X, ensure_min_features=min_value_cols, dtype=None, force_all_finite=False) | ||
def parse_X_y(X, y, groups, check_X=True, **kwargs) -> nw.DataFrame: | ||
"""Converts X, y to narwhals dataframe. | ||
|
||
try: | ||
if isinstance(X, pd.DataFrame): | ||
X_group = X.loc[:, groups] | ||
X_value = X.drop(columns=groups).values | ||
else: | ||
X = np.asarray(X) # deals with `_NotAnArray` case | ||
X_group = pd.DataFrame(X[:, groups]) | ||
pos_indexes = range(X.shape[1]) | ||
X_value = np.delete(X, [pos_indexes[g] for g in groups], axis=1) | ||
except (KeyError, IndexError): | ||
raise ValueError(f"Could not drop groups {groups} from columns of X") | ||
If it is not a supported dataframe, it uses pandas constructor as a fallback. | ||
|
||
X_group = _check_grouping_columns(X_group, **kwargs) | ||
Additionally, data checks are performed. | ||
""" | ||
# Check raw X | ||
_data_format_checks(X) | ||
|
||
if check_X: | ||
X_value = check_array(X_value, **kwargs) | ||
# Convert X to Narwhals frame | ||
X = nw.from_native(X, strict=False, eager_only=True) | ||
if not isinstance(X, nw.DataFrame): | ||
X = nw.from_native(pd.DataFrame(X)) | ||
|
||
return X_group, X_value | ||
# Check groups and feaures values | ||
if groups is not None: | ||
_validate_groups_values(X, groups) | ||
|
||
if check_X: | ||
check_array(X.drop(groups), **kwargs) | ||
|
||
def _data_format_checks(X, name): | ||
_ensure_no_complex_data(X) | ||
# Convert y and assign it to the frame | ||
n_samples = X.shape[0] | ||
native_space = nw.get_native_namespace(X) | ||
|
||
y_native = native_space.Series([None] * n_samples) if y is None else native_space.Series(y) | ||
return X.with_columns(__sklego_target__=nw.from_native(y_native, allow_series=True)) | ||
|
||
if issparse(X): # sklearn.validation._ensure_sparse_format to complicated | ||
raise ValueError(f"The estimator {name} does not work on sparse matrices") | ||
|
||
def _validate_groups_values(X: nw.DataFrame, groups: List[int] | List[str]) -> None: | ||
X_cols = X.columns | ||
unexisting_cols = [g for g in groups if g not in X_cols] | ||
|
||
def _check_grouping_columns(X_group, **kwargs) -> pd.DataFrame: | ||
"""Do basic checks on grouping columns""" | ||
# Do regular checks on numeric columns | ||
X_group_num = X_group.select_dtypes(include="number") | ||
if X_group_num.shape[1]: | ||
check_array(X_group_num, **kwargs) | ||
if len(unexisting_cols): | ||
raise ValueError(f"The following groups are not available in X: {unexisting_cols}") | ||
|
||
# Only check missingness in object columns | ||
if X_group.select_dtypes(exclude="number").isnull().any(axis=None): | ||
raise ValueError("X has NaN values") | ||
if X.select(nw.col(groups).is_null().any()).to_numpy().squeeze().any(): | ||
raise ValueError("Groups values have NaN") | ||
|
||
# The grouping part we always want as a DataFrame with range index | ||
return X_group.reset_index(drop=True) | ||
|
||
def _data_format_checks(X): | ||
"""Checks that X is not sparse nor has complex dtype""" | ||
_ensure_no_complex_data(X) | ||
|
||
if issparse(X): # sklearn.validation._ensure_sparse_format to complicated | ||
msg = "Estimator does not work on sparse matrices" | ||
raise ValueError(msg) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can this go away once we have it in main?