-
Notifications
You must be signed in to change notification settings - Fork 23
feat(pkg-py): Replace pandas with narwhals #175
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
Open
cpsievert
wants to merge
2
commits into
main
Choose a base branch
from
feat/narwhals-df
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -5,12 +5,12 @@ | |
|
|
||
| import duckdb | ||
| import narwhals.stable.v1 as nw | ||
| import pandas as pd | ||
| from sqlalchemy import inspect, text | ||
| from sqlalchemy.sql import sqltypes | ||
|
|
||
| from ._df_compat import duckdb_result_to_nw, read_sql | ||
|
|
||
| if TYPE_CHECKING: | ||
| from narwhals.stable.v1.typing import IntoFrame | ||
| from sqlalchemy.engine import Connection, Engine | ||
|
|
||
|
|
||
|
|
@@ -53,7 +53,7 @@ def get_schema(self, *, categorical_threshold: int) -> str: | |
| ... | ||
|
|
||
| @abstractmethod | ||
| def execute_query(self, query: str) -> pd.DataFrame: | ||
| def execute_query(self, query: str) -> nw.DataFrame: | ||
| """ | ||
| Execute SQL query and return results as DataFrame. | ||
|
|
||
|
|
@@ -65,20 +65,20 @@ def execute_query(self, query: str) -> pd.DataFrame: | |
| Returns | ||
| ------- | ||
| : | ||
| Query results as a pandas DataFrame | ||
| Query results as a narwhals DataFrame | ||
|
|
||
| """ | ||
| ... | ||
|
|
||
| @abstractmethod | ||
| def get_data(self) -> pd.DataFrame: | ||
| def get_data(self) -> nw.DataFrame: | ||
| """ | ||
| Return the unfiltered data as a DataFrame. | ||
|
|
||
| Returns | ||
| ------- | ||
| : | ||
| The complete dataset as a pandas DataFrame | ||
| The complete dataset as a narwhals DataFrame | ||
|
|
||
| """ | ||
| ... | ||
|
|
@@ -99,27 +99,26 @@ def cleanup(self) -> None: | |
|
|
||
|
|
||
| class DataFrameSource(DataSource): | ||
| """A DataSource implementation that wraps a pandas DataFrame using DuckDB.""" | ||
| """A DataSource implementation that wraps a DataFrame using DuckDB.""" | ||
|
|
||
| _df: nw.DataFrame | nw.LazyFrame | ||
| _df: nw.DataFrame | ||
|
|
||
| def __init__(self, df: IntoFrame, table_name: str): | ||
| def __init__(self, df: nw.DataFrame, table_name: str): | ||
| """ | ||
| Initialize with a pandas DataFrame. | ||
| Initialize with a DataFrame. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| df | ||
| The DataFrame to wrap | ||
| The DataFrame to wrap (pandas, polars, or any narwhals-compatible frame) | ||
| table_name | ||
| Name of the table in SQL queries | ||
|
|
||
| """ | ||
| self._conn = duckdb.connect(database=":memory:") | ||
| self._df = nw.from_native(df) | ||
| self._df = nw.from_native(df) if not isinstance(df, nw.DataFrame) else df | ||
| self.table_name = table_name | ||
| # TODO(@gadenbuie): If the data frame is already SQL-backed, maybe we shouldn't be making a new copy here. | ||
| self._conn.register(table_name, self._df.lazy().collect().to_pandas()) | ||
| self._conn.register(table_name, self._df.to_native()) | ||
|
|
||
| def get_db_type(self) -> str: | ||
| """ | ||
|
|
@@ -151,16 +150,8 @@ def get_schema(self, *, categorical_threshold: int) -> str: | |
| """ | ||
| schema = [f"Table: {self.table_name}", "Columns:"] | ||
|
|
||
| # Ensure we're working with a DataFrame, not a LazyFrame | ||
| ndf = ( | ||
| self._df.head(10).collect() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note that downstream calculation of ranges and unique values wasn't working properly because they were based on the first 10 rows -- I'll address this when doing the new |
||
| if isinstance(self._df, nw.LazyFrame) | ||
| else self._df | ||
| ) | ||
|
|
||
| for column in ndf.columns: | ||
| # Map pandas dtypes to SQL-like types | ||
| dtype = ndf[column].dtype | ||
| for column in self._df.columns: | ||
| dtype = self._df[column].dtype | ||
| if dtype.is_integer(): | ||
| sql_type = "INTEGER" | ||
| elif dtype.is_float(): | ||
|
|
@@ -176,17 +167,14 @@ def get_schema(self, *, categorical_threshold: int) -> str: | |
|
|
||
| column_info = [f"- {column} ({sql_type})"] | ||
|
|
||
| # For TEXT columns, check if they're categorical | ||
| if sql_type == "TEXT": | ||
| unique_values = ndf[column].drop_nulls().unique() | ||
| unique_values = self._df[column].drop_nulls().unique() | ||
| if unique_values.len() <= categorical_threshold: | ||
| categories = unique_values.to_list() | ||
| categories_str = ", ".join([f"'{c}'" for c in categories]) | ||
| column_info.append(f" Categorical values: {categories_str}") | ||
|
|
||
| # For numeric columns, include range | ||
| elif sql_type in ["INTEGER", "FLOAT", "DATE", "TIME"]: | ||
| rng = ndf[column].min(), ndf[column].max() | ||
| rng = self._df[column].min(), self._df[column].max() | ||
| if rng[0] is None and rng[1] is None: | ||
| column_info.append(" Range: NULL to NULL") | ||
| else: | ||
|
|
@@ -196,10 +184,12 @@ def get_schema(self, *, categorical_threshold: int) -> str: | |
|
|
||
| return "\n".join(schema) | ||
|
|
||
| def execute_query(self, query: str) -> pd.DataFrame: | ||
| def execute_query(self, query: str) -> nw.DataFrame: | ||
| """ | ||
| Execute query using DuckDB. | ||
|
|
||
| Uses polars if available, otherwise falls back to pandas. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| query | ||
|
|
@@ -208,23 +198,22 @@ def execute_query(self, query: str) -> pd.DataFrame: | |
| Returns | ||
| ------- | ||
| : | ||
| Query results as pandas DataFrame | ||
| Query results as narwhals DataFrame | ||
|
|
||
| """ | ||
| return self._conn.execute(query).df() | ||
| return duckdb_result_to_nw(self._conn.execute(query)) | ||
|
|
||
| def get_data(self) -> pd.DataFrame: | ||
| def get_data(self) -> nw.DataFrame: | ||
| """ | ||
| Return the unfiltered data as a DataFrame. | ||
|
|
||
| Returns | ||
| ------- | ||
| : | ||
| The complete dataset as a pandas DataFrame | ||
| The complete dataset as a narwhals DataFrame | ||
|
|
||
| """ | ||
| # TODO(@gadenbuie): This should just return `self._df` and not a pandas DataFrame | ||
| return self._df.lazy().collect().to_pandas() | ||
| return self._df | ||
|
|
||
| def cleanup(self) -> None: | ||
| """ | ||
|
|
@@ -412,10 +401,12 @@ def get_schema(self, *, categorical_threshold: int) -> str: # noqa: PLR0912 | |
|
|
||
| return "\n".join(schema) | ||
|
|
||
| def execute_query(self, query: str) -> pd.DataFrame: | ||
| def execute_query(self, query: str) -> nw.DataFrame: | ||
| """ | ||
| Execute SQL query and return results as DataFrame. | ||
|
|
||
| Uses polars if available, otherwise falls back to pandas. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| query | ||
|
|
@@ -424,20 +415,20 @@ def execute_query(self, query: str) -> pd.DataFrame: | |
| Returns | ||
| ------- | ||
| : | ||
| Query results as pandas DataFrame | ||
| Query results as narwhals DataFrame | ||
|
|
||
| """ | ||
| with self._get_connection() as conn: | ||
| return pd.read_sql_query(text(query), conn) | ||
| return read_sql(text(query), conn) | ||
|
|
||
| def get_data(self) -> pd.DataFrame: | ||
| def get_data(self) -> nw.DataFrame: | ||
| """ | ||
| Return the unfiltered data as a DataFrame. | ||
|
|
||
| Returns | ||
| ------- | ||
| : | ||
| The complete dataset as a pandas DataFrame | ||
| The complete dataset as a narwhals DataFrame | ||
|
|
||
| """ | ||
| return self.execute_query(f"SELECT * FROM {self.table_name}") | ||
|
|
||
This file contains hidden or 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 |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| """ | ||
| DataFrame compatibility: try polars first, fall back to pandas. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| import narwhals.stable.v1 as nw | ||
|
|
||
| if TYPE_CHECKING: | ||
| import duckdb | ||
| from sqlalchemy.engine import Connection | ||
| from sqlalchemy.sql.elements import TextClause | ||
|
|
||
| _INSTALL_MSG = "Install one with: pip install polars OR pip install pandas" | ||
|
|
||
|
|
||
| def read_sql(query: TextClause, conn: Connection) -> nw.DataFrame: | ||
| try: | ||
| import polars as pl # noqa: PLC0415 # pyright: ignore[reportMissingImports] | ||
|
|
||
| return nw.from_native(pl.read_database(query, connection=conn)) | ||
| except Exception: # noqa: S110 | ||
| # Catches ImportError for polars, and other errors (e.g., missing pyarrow) | ||
| # Intentional fallback to pandas - no logging needed | ||
| pass | ||
|
|
||
| try: | ||
| import pandas as pd # noqa: PLC0415 # pyright: ignore[reportMissingImports] | ||
|
|
||
| return nw.from_native(pd.read_sql_query(query, conn)) | ||
| except ImportError: | ||
| pass | ||
|
|
||
| raise ImportError(f"SQLAlchemySource requires 'polars' or 'pandas'. {_INSTALL_MSG}") | ||
|
|
||
|
|
||
| def duckdb_result_to_nw( | ||
| result: duckdb.DuckDBPyRelation | duckdb.DuckDBPyConnection, | ||
| ) -> nw.DataFrame: | ||
| try: | ||
| return nw.from_native(result.pl()) | ||
| except Exception: # noqa: S110 | ||
| # Catches ImportError for polars, and other errors (e.g., missing pyarrow) | ||
| # Intentional fallback to pandas - no logging needed | ||
| pass | ||
|
|
||
| try: | ||
| return nw.from_native(result.df()) | ||
| except ImportError: | ||
| pass | ||
|
|
||
| raise ImportError(f"DataFrameSource requires 'polars' or 'pandas'. {_INSTALL_MSG}") | ||
|
|
||
|
|
||
| def read_csv(path: str) -> nw.DataFrame: | ||
| try: | ||
| import polars as pl # noqa: PLC0415 # pyright: ignore[reportMissingImports] | ||
|
|
||
| return nw.from_native(pl.read_csv(path)) | ||
| except Exception: # noqa: S110 | ||
| # Catches ImportError for polars, and other errors (e.g., missing pyarrow) | ||
| # Intentional fallback to pandas - no logging needed | ||
| pass | ||
|
|
||
| try: | ||
| import pandas as pd # noqa: PLC0415 # pyright: ignore[reportMissingImports] | ||
|
|
||
| return nw.from_native(pd.read_csv(path, compression="gzip")) | ||
| except ImportError: | ||
| pass | ||
|
|
||
| raise ImportError(f"Loading data requires 'polars' or 'pandas'. {_INSTALL_MSG}") |
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
I'm pretty sure it's going to make sense for us to have a separate
LazyFrameSource, which I'll do in a follow up PR (before the next release). The benefit being that we can be more lazy about computation, and possibly have.df()also return aLazyFramein that scenario