Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
feaad95
concat
FBruzzesi Apr 8, 2025
f28599f
seems to work
FBruzzesi Apr 8, 2025
fc982d3
copy=False
FBruzzesi Apr 8, 2025
f557dd5
ok pandas 3
FBruzzesi Apr 9, 2025
46c29e7
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 9, 2025
d5fea77
do not HACK non-pandas codepath
FBruzzesi Apr 9, 2025
f3b4cf9
mypy
FBruzzesi Apr 9, 2025
9f3c415
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 10, 2025
bd7fd09
refactor: `utils.horizontal_concat` -> `Namespace._horizontal_concat`
dangotbanned Apr 10, 2025
987a688
revert: undo last commit
dangotbanned Apr 10, 2025
7f39ada
re-solve conflicts
FBruzzesi Apr 17, 2025
0d105a3
re-solve conflicts
FBruzzesi Apr 17, 2025
13166e7
fix pandas utils
FBruzzesi Apr 17, 2025
afaa9ec
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 18, 2025
2cf041c
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 19, 2025
984a57b
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 20, 2025
823293b
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 21, 2025
788bc1f
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi Apr 29, 2025
1e745d4
merge main
FBruzzesi May 2, 2025
e1ef8b5
Merge branch 'main' into fix/maintain-pandas-column-index-name
FBruzzesi May 3, 2025
28795f2
Merge remote-tracking branch 'upstream/main' into fix/maintain-pandas…
MarcoGorelli May 16, 2025
5efaff2
keep it simpler, dont trust pandas for rename_axis
MarcoGorelli May 16, 2025
f202c57
remove unintended file
MarcoGorelli May 16, 2025
e024c54
reduce diff
MarcoGorelli May 16, 2025
5387649
reduce diff
MarcoGorelli May 16, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion narwhals/_dask/dataframe.py

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dask select and with_columns have no issues since we use .assign method for both!

Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from narwhals._dask.utils import add_row_index
from narwhals._dask.utils import evaluate_exprs
from narwhals._pandas_like.utils import native_to_narwhals_dtype
from narwhals._pandas_like.utils import rename_axis
from narwhals._pandas_like.utils import select_columns_by_name
from narwhals.typing import CompliantDataFrame
from narwhals.typing import CompliantLazyFrame
Expand Down Expand Up @@ -112,7 +113,12 @@ def collect(
from narwhals._pandas_like.dataframe import PandasLikeDataFrame

return PandasLikeDataFrame(
result,
rename_axis(
result,
implementation=Implementation.PANDAS,
backend_version=parse_version(pd),
columns=self.native.columns.name,
),
implementation=Implementation.PANDAS,
backend_version=parse_version(pd),
Comment thread
FBruzzesi marked this conversation as resolved.
version=self._version,
Expand Down
16 changes: 14 additions & 2 deletions narwhals/_pandas_like/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from narwhals._pandas_like.utils import object_native_to_narwhals_dtype
from narwhals._pandas_like.utils import pivot_table
from narwhals._pandas_like.utils import rename
from narwhals._pandas_like.utils import rename_axis
from narwhals._pandas_like.utils import select_columns_by_name
from narwhals._pandas_like.utils import set_index
from narwhals.dependencies import is_numpy_array_1d
Expand Down Expand Up @@ -120,6 +121,7 @@ def __init__(
validate_backend_version(self._implementation, self._backend_version)
if validate_column_names:
check_column_names_are_unique(native_dataframe.columns)
self._native_columns_name = native_dataframe.columns.name

@classmethod
def from_arrow(cls, data: IntoArrowTable, /, *, context: _FullContext) -> Self:
Expand Down Expand Up @@ -251,7 +253,12 @@ def _with_version(self: Self, version: Version) -> Self:

def _with_native(self: Self, df: Any, *, validate_column_names: bool = True) -> Self:
return self.__class__(
df,
rename_axis(
df,
implementation=self._implementation,
backend_version=self._backend_version,
columns=self._native_columns_name,
),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ€” i'm wondering if we could/should just set df.columns.name = self._native_columns_name

else we need to trust pandas' copy-on-write / copy=False working properly, which i'm not sure i do

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I trust your judgement here - but should I would be concerned as a pandas user?

implementation=self._implementation,
backend_version=self._backend_version,
version=self._version,
Expand Down Expand Up @@ -633,7 +640,12 @@ def collect(
import pandas as pd # ignore-banned-import

return PandasLikeDataFrame(
self.to_pandas(),
rename_axis(
self.to_pandas(),
implementation=self._implementation,
backend_version=self._backend_version,
columns=self._native_columns_name,
),
implementation=Implementation.PANDAS,
backend_version=parse_version(pd),
version=self._version,
Expand Down
46 changes: 18 additions & 28 deletions narwhals/_pandas_like/namespace.py
Comment thread
FBruzzesi marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -228,43 +228,33 @@ def concat(
) -> PandasLikeDataFrame:
dfs: list[Any] = [item._native_frame for item in items]
if how == "horizontal":
return PandasLikeDataFrame(
horizontal_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
),
native_dataframe = horizontal_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
version=self._version,
validate_column_names=True,
)
if how == "vertical":
return PandasLikeDataFrame(
vertical_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
),
elif how == "vertical":
native_dataframe = vertical_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
version=self._version,
validate_column_names=True,
)

if how == "diagonal":
return PandasLikeDataFrame(
diagonal_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
),
elif how == "diagonal":
native_dataframe = diagonal_concat(
dfs,
implementation=self._implementation,
backend_version=self._backend_version,
version=self._version,
validate_column_names=True,
)
raise NotImplementedError
else:
raise NotImplementedError

return PandasLikeDataFrame(
native_dataframe,
implementation=self._implementation,
backend_version=self._backend_version,
version=self._version,
validate_column_names=True,
)

def when(self: Self, predicate: PandasLikeExpr) -> PandasWhen:
return PandasWhen.from_expr(predicate, context=self)
Expand Down
15 changes: 15 additions & 0 deletions narwhals/_pandas_like/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,21 @@ def check_column_names_are_unique(columns: pd.Index[str]) -> None:
raise DuplicateError(msg)


def rename_axis(
obj: T,
*args: Any,
implementation: Implementation,
backend_version: tuple[int, ...],
**kwargs: Any,
) -> T:
"""Wrapper around pandas' rename_axis so that we can set `copy` based on implementation/version."""
if implementation is Implementation.PANDAS and (
backend_version >= (3,)
): # pragma: no cover
return obj.rename_axis(*args, **kwargs) # type: ignore[attr-defined]
return obj.rename_axis(*args, **kwargs, copy=False) # type: ignore[attr-defined]


class PandasLikeSeriesNamespace(EagerSeriesNamespace["PandasLikeSeries", Any]):
@property
def implementation(self) -> Implementation:
Expand Down
2 changes: 1 addition & 1 deletion narwhals/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,8 +488,8 @@ def _from_native_impl( # noqa: PLR0915
return DataFrame(
PandasLikeDataFrame(
native_object,
backend_version=parse_version(pd),
implementation=Implementation.PANDAS,
backend_version=parse_version(pd),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mental sanity for symmetry with other pandas-like and order of the spec πŸ˜…

version=version,
validate_column_names=True,
),
Expand Down
12 changes: 7 additions & 5 deletions tests/frame/join_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import narwhals as nw_main # use nw_main in some tests for coverage
import narwhals.stable.v1 as nw
from narwhals.utils import Implementation
from tests.utils import DUCKDB_VERSION
from tests.utils import PANDAS_VERSION
from tests.utils import POLARS_VERSION
Expand Down Expand Up @@ -238,11 +237,14 @@ def test_cross_join_suffix(


def test_cross_join_non_pandas() -> None:
_ = pytest.importorskip("modin")

import modin.pandas as mpd

data = {"antananarivo": [1, 3, 2]}
df = nw.from_native(pd.DataFrame(data))
# HACK to force testing for a non-pandas codepath
df._compliant_frame._implementation = Implementation.MODIN
result = df.join(df, how="cross") # type: ignore[arg-type]
df1 = nw.from_native(mpd.DataFrame(pd.DataFrame(data)), eager_only=True)
df2 = nw.from_native(mpd.DataFrame(pd.DataFrame(data)), eager_only=True)
result = df1.join(df2, how="cross")
expected = {
"antananarivo": [1, 1, 1, 3, 3, 3, 2, 2, 2],
"antananarivo_right": [1, 3, 2, 1, 3, 2, 1, 3, 2],
Expand Down
28 changes: 28 additions & 0 deletions tests/preserve_pandas_like_columns_name_attr_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

import narwhals.stable.v1 as nw

if TYPE_CHECKING:
from tests.utils import Constructor


def test_ops_preserve_column_index_name(constructor: Constructor) -> None:
if not any(x in str(constructor) for x in ("pandas", "modin", "cudf", "dask")):
pytest.skip(
reason="Dataframe columns is a list and do not have a `name` like a pandas Index does"
)

data = {"a": [1, 3, 2], "b": [4, 4, 6], "z": [7.0, 8.0, 9.0]}
df_native = constructor(data)
df_native.columns.name = "foo" # type: ignore[union-attr]

df = nw.from_native(df_native)

result = df.with_columns(b=nw.col("a") + 1, c=nw.col("a") * 2).select("c", "b")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to concatenate two methods here, mostly for the sake of it.
Might be worth reparametrizing it


assert result.to_native().columns.name == "foo" # type: ignore[union-attr]
assert result.lazy().collect(backend="pandas").to_native().columns.name == "foo"