This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 0c074505 [SPARK-61244][CONNECT][PYTHON] Convert pandas frames with 
MultiIndex or CategoricalIndex labels through Arrow, as PySpark does
0c074505 is described below

commit 0c074505a241a7a081223a4ac9ce10a567af6f49
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:42:25 2026 +0900

    [SPARK-61244][CONNECT][PYTHON] Convert pandas frames with MultiIndex or 
CategoricalIndex labels through Arrow, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61244](https://issues.apache.org/jira/browse/SPARK-61244): Convert 
pandas frames with MultiIndex or CategoricalIndex labels through Arrow, as 
PySpark does.
    
    - A pandas frame whose column labels are a plain `pd.MultiIndex` or 
`pd.CategoricalIndex` now takes the Arrow routes of `createDataFrame` (explicit 
schema, names, or inferred schema), as frames with a default `RangeIndex` 
already do. The check is `_has_canonical_columns`, which accepts these labels 
when they have the override rules of an `Index` (the exact class, no 
`__getattribute__`, `__iter__` or `__len__` override on the class or the 
instance, pandas' own values), and when their s [...]
    - Official PySpark 4.3.0 names such columns by `str` of the label (`('a', 
'x')`), which the Arrow routes already do. Naive datetimes in a list become 
`array<timestamp_ntz>`, Decimal lists take the smallest precision and scale, 
and dict cells are structs of the value types of their keys (a map only under 
`spark.sql.execution.pandas.inferPandasDictAsMap`), as PySpark does. The row 
path gave `array<timestamp>` (shifted by the session time zone), 
`decimal(38,s)`, a map, or `Type mismatch  [...]
    - Subclassed frames and the other label kinds keep the row path, as before: 
a subclass can override any method the Arrow routes call, so its method order 
stays that of the row path.
    - The Row scan of object columns (`inferred_pandas_row_columns`) skips a 
column whose cells all have exact builtin scalar types, by comparing the 
identities of their types (hashing a type could run a metaclass hook). Such a 
column holds no Row, so the result is unchanged. For the row-path frames that 
remain, the scan of a 10k x 5 object frame takes about 4-5 ms instead of about 
15-17 ms.
    
    Measured on a local Spark 4.3.0 server (UTC), 10k x 5 object strings, 
median of 5 runs, under a heavily loaded machine: MultiIndex str 31 ms before, 
5 ms after (official 4.8 ms); CategoricalIndex str 32 ms before, 10 ms after; a 
subclass of DataFrame 32 ms before, 19 ms after (it keeps the row path); a 
plain named frame and a default RangeIndex frame are unchanged.
    
    ### Why are the changes needed?
    
    A pandas frame whose labels were a plain MultiIndex or CategoricalIndex 
took the native row path, which converts cells differently from PySpark:
    
    - `spark.createDataFrame(pd.DataFrame([[[datetime(2020, 1, 2, 3)]]], 
columns=pd.MultiIndex.from_tuples([("a", "x")])))` under 
`spark.sql.session.timeZone=Asia/Seoul` read back as `2020-01-02 12:00:00`: the 
naive datetime was taken as a time of the session time zone, and the list type 
was `array<timestamp>`. PySpark gives `array<timestamp_ntz>` and reads back 
`2020-01-02 03:00:00`.
    - A list of `Decimal("1.5"), Decimal("10.25")` became 
`array<decimal(38,2)>`; PySpark gives `array<decimal(4,2)>`.
    - `spark.createDataFrame(pd.DataFrame([[{"u": 1, "v": "a"}]], 
columns=pd.MultiIndex.from_tuples([("a", "x")])))` failed with 
`PySparkRuntimeError: Type mismatch in row data`; PySpark gives 
`struct<u:bigint,v:string>`. The same frame with `{"u": 1, "v": 2}` gave a map; 
PySpark gives a struct.
    - The Row scan that 60bb98ea added to the row path made frames of object 
string columns about 2.7x slower than before that change.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Plain MultiIndex and CategoricalIndex column labels of a pandas frame 
now convert as PySpark converts them: the types of list, Decimal and dict 
cells, and the session time zone of naive datetimes, match PySpark 4.3.0. 
Subclassed frames are unchanged.
    
    ### How was this patch tested?
    
    - `test_multi_and_categorical_labels_convert_cells_as_pyspark` (offline, 12 
cases: 2- and 3-level MultiIndex and CategoricalIndex labels, each with a naive 
datetime list, a Decimal list, a mixed dict and a same-key dict): the Arrow 
type of the cells is the one PySpark infers (`list<timestamp[us]>`, 
`list<decimal128(4, 2)>`, `struct<u: int64, v: string>`, `struct<u: int64, v: 
int64>`) and the values are unchanged. All 12 fail without this change and pass 
with it.
    - `test_create_dataframe_of_multi_and_categorical_labels_as_pyspark` 
(live): with `spark.sql.session.timeZone=Asia/Seoul`, the names are the labels 
as strings, the schemas are PySpark's (`array<timestamp_ntz>`, 
`array<decimal(4,2)>`, `struct<u:bigint,v:string>`, 
`struct<u:bigint,v:bigint>`), and the naive datetime reads back as `2020-01-02 
03:00:00`. It fails without this change (`Type mismatch in row data`), and the 
same schemas and values were checked against official PySpark 4.3.0  [...]
    - Probes against official PySpark 4.3.0 over MultiIndex (2 and 3 levels, 
int, mixed, duplicate and `None` labels, empty frames), CategoricalIndex (str, 
int, mixed, duplicate labels), with no schema, a DDL or StructType schema, 
names, `inferPandasDictAsMap`, and `spark.sql.execution.arrow.pyspark.enabled` 
on and off, under UTC and Asia/Seoul: the results and errors are identical, 
except a MultiIndex with a `DatetimeIndex` level, which keeps the row path.
    - The offline Python suites (2831 passed, 8 skipped), the new tests also 
under pytest 9.2, and the live drop-in tests `-k pandas` (19 passed) against a 
local Spark 4.3.0 server. No Rust code changes.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #422 from HyukjinKwon/SPARK-61244-pandas-structured-labels.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 python/pyspark/sql/_pandas_input.py | 76 +++++++++++++++++++++++++++++++++----
 python/tests/test_dropin_e2e.py     | 34 +++++++++++++++++
 python/tests/test_dropin_offline.py | 32 ++++++++++++++++
 3 files changed, 135 insertions(+), 7 deletions(-)

diff --git a/python/pyspark/sql/_pandas_input.py 
b/python/pyspark/sql/_pandas_input.py
index 538db6a2..c2773729 100644
--- a/python/pyspark/sql/_pandas_input.py
+++ b/python/pyspark/sql/_pandas_input.py
@@ -159,6 +159,50 @@ def _has_canonical_range_columns(columns, range_module):
     return type(vars(columns).get("_range")) is range
 
 
+def _has_canonical_structured_columns(columns, module, multi):
+    """Accept a plain MultiIndex or CategoricalIndex of column labels, as an 
Index is accepted.
+
+    The labels only name the columns, and the Arrow routes name them as 
PySpark does, by `str`.
+    The override rules of an Index apply: the exact class, no override of 
`__getattribute__`,
+    `__iter__` or `__len__` on the class or the instance, and pandas' own 
iteration and values.
+    The storage must be pandas' own too: the levels and codes of a MultiIndex, 
and the values
+    and categories of a CategoricalIndex. Each label container inside is 
checked as an Index.
+    """
+    import numpy as np
+    from pandas.core import base as base_module
+    from pandas.core.arrays import categorical as categorical_module
+    from pandas.core.indexes import base as index_module, frozen as 
frozen_module
+
+    cls = type(columns)
+    if (cls.__getattribute__ is not object.__getattribute__
+            or "__iter__" in vars(columns) or "__len__" in vars(columns)
+            or cls.__iter__ is not base_module.IndexOpsMixin.__iter__
+            or not _defined_in(base_module.IndexOpsMixin.__iter__, "__iter__", 
base_module)
+            or not _defined_in(cls.__len__, "__len__", module, index_module)):
+        return False
+    _, values = _raw_class_attribute(cls, "_values")
+    if not _defined_in(getattr(values, "fget", None), "_values", module, 
index_module,
+                       base_module):
+        return False
+
+    if multi:
+        levels = vars(columns).get("_levels")
+        codes = vars(columns).get("_codes")
+        if (type(levels) is not frozen_module.FrozenList
+                or type(codes) is not frozen_module.FrozenList):
+            return False
+        return (all(_has_canonical_columns(level) for level in 
list.__iter__(levels))
+                and all(type(code) is np.ndarray for code in 
list.__iter__(codes)))
+
+    data = vars(columns).get("_data")
+    categorical = categorical_module.Categorical
+    if (type(data) is not categorical or "__iter__" in vars(data)
+            or not _defined_in(categorical.__iter__, "__iter__", 
categorical_module)):
+        return False
+    # Read the categories through the pandas property, not an instance 
attribute.
+    return _has_canonical_columns(categorical.categories.__get__(data))
+
+
 def _has_canonical_columns(columns):
     """Decline label containers whose row-path iteration can run custom 
hooks."""
     import sys
@@ -167,12 +211,21 @@ def _has_canonical_columns(columns):
     import pandas as pd
     from pandas.core import base as base_module
     from pandas.core.indexes import base as index_module
+    from pandas.core.indexes import category as category_module, multi as 
multi_module
     from pandas.core.indexes import range as range_module
 
     # A default RangeIndex (pd.DataFrame of a list or ndarray) takes the Arrow 
routes too.
     if pd.RangeIndex is range_module.RangeIndex and type(columns) is 
pd.RangeIndex:
         return _has_canonical_range_columns(columns, range_module)
 
+    # Plain MultiIndex and CategoricalIndex labels (`pd.DataFrame` with tuples 
or categories)
+    # take the Arrow routes too: their labels are only names, as with a 
default RangeIndex.
+    if pd.MultiIndex is multi_module.MultiIndex and type(columns) is 
pd.MultiIndex:
+        return _has_canonical_structured_columns(columns, multi_module, True)
+    if (pd.CategoricalIndex is category_module.CategoricalIndex
+            and type(columns) is pd.CategoricalIndex):
+        return _has_canonical_structured_columns(columns, category_module, 
False)
+
     Index = index_module.Index
     if (pd.Index is not Index or type(columns) is not Index
             or Index.__getattribute__ is not object.__getattribute__
@@ -1118,10 +1171,11 @@ def _canonical_struct(schema):
 def accepts_pandas_table(frame, schema):
     """Whether `prepare_pandas_table` may convert this frame under this schema.
 
-    Customized frames, column labels, schema classes and rebound type names 
keep the row
-    path, which reads them in its own order. Conversion-hook authentication 
covers Arrow
-    string storage, including inherited hooks. Other pandas arrays retain the 
existing
-    module-origin checks; rebinding their canonical classes' hooks is not 
covered here.
+    Customized frames, column labels that are not plain (see 
`_has_canonical_columns`),
+    schema classes and rebound type names keep the row path, which reads them 
in its own
+    order. Conversion-hook authentication covers Arrow string storage, 
including inherited
+    hooks. Other pandas arrays retain the existing module-origin checks; 
rebinding their
+    canonical classes' hooks is not covered here.
     The conversion and importer resolve type names by lookup, so each 
namespace must hold
     the native classes. The schema is the caller's object or a DDL string, 
which is parsed.
     """
@@ -1402,15 +1456,23 @@ def inferred_pandas_row_columns(rows, width, 
candidates=None):
 
     if any(type(row) is not list or len(row) != width for row in 
list.__iter__(rows)):
         return []
+    # Identities of the exact builtin scalar types. A column whose cells have 
only these
+    # types holds no Row, so its cells are not walked. Compare identities, not 
types:
+    # hashing a type could run a metaclass hook.
+    scalar_ids = frozenset(map(id, (type(None), bool, int, float, complex, 
str, bytes,
+                                    bytearray)))
     columns = []
     for index in range(width) if candidates is None else candidates:
+        cells = [row[index] for row in list.__iter__(rows)]
+        if set(map(id, map(type, cells))) <= scalar_ids:
+            continue
         values = None
         try:
-            for row_index, row in enumerate(list.__iter__(rows)):
-                converted = positional(row[index])
+            for row_index, cell in enumerate(cells):
+                converted = positional(cell)
                 if converted is not unchanged:
                     if values is None:
-                        values = [item[index] for item in list.__iter__(rows)]
+                        values = list(cells)
                     values[row_index] = converted
         except Exception as error:
             # Retain the column index so an earlier native failure still wins.
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e00e91f9..3cfc13e4 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2320,6 +2320,40 @@ def 
test_variant_spatial_and_user_defined_values_round_trip_as_pyspark(session):
     assert geometry == Geometry.fromWKB(wkb, 0)
 
 
+def test_create_dataframe_of_multi_and_categorical_labels_as_pyspark(session):
+    # As PySpark's: a frame whose labels are a MultiIndex or a 
CategoricalIndex converts its
+    # cells as a frame of default labels does. A naive datetime of a list 
reads back unchanged
+    # under a session time zone other than UTC, the Decimals and dicts take 
PySpark's types, and
+    # the names are the labels as strings.
+    import pandas as pd
+
+    cells = [[datetime(2020, 1, 2, 3)], [Decimal("1.5"), Decimal("10.25")],
+             {"u": 1, "v": "a"}, {"u": 1, "v": 2}]
+    frames = [
+        (pd.DataFrame([cells], columns=pd.MultiIndex.from_tuples(
+            [("a", "x"), ("b", "y"), ("c", "z"), ("d", "w")]), dtype=object),
+         ["('a', 'x')", "('b', 'y')", "('c', 'z')", "('d', 'w')"]),
+        (pd.DataFrame([cells], columns=pd.CategoricalIndex(["a", "b", "c", 
"d"]), dtype=object),
+         ["a", "b", "c", "d"]),
+    ]
+    previous = session.conf.get("spark.sql.session.timeZone")
+    session.conf.set("spark.sql.session.timeZone", "Asia/Seoul")
+    try:
+        for frame, names in frames:
+            df = session.createDataFrame(frame)
+            assert df.columns == names
+            assert df.schema.fields[0].dataType.simpleString() == 
"array<timestamp_ntz>"
+            assert df.schema.fields[1].dataType.simpleString() == 
"array<decimal(4,2)>"
+            assert df.schema.fields[2].dataType.simpleString() == 
"struct<u:bigint,v:string>"
+            assert df.schema.fields[3].dataType.simpleString() == 
"struct<u:bigint,v:bigint>"
+            row = df.first()
+            assert row[0] == [datetime(2020, 1, 2, 3)]
+            assert row[1] == [Decimal("1.50"), Decimal("10.25")]
+            assert row[2] == Row(u=1, v="a") and row[3] == Row(u=1, v=2)
+    finally:
+        session.conf.set("spark.sql.session.timeZone", previous)
+
+
 def 
test_create_dataframe_of_pandas_infers_the_types_of_arrow_as_pyspark(session):
     # As PySpark Connect's: without a schema, the columns of a pandas 
DataFrame convert with
     # PySpark's Arrow conversion, of the types that Arrow infers, and a naive 
datetime is a time
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 23550788..b35f2d7b 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7850,6 +7850,38 @@ def 
test_create_dataframe_name_width_errors_as_pyspark(data, schema, expected, a
         "expected_length": expected, "actual_length": actual}
 
 
[email protected]("labels", ["multi2", "multi3", "categorical"])
[email protected]("cell, arrow_type", [
+    # A naive datetime of a list is a timestamp_ntz, not a time of the session 
time zone.
+    ([datetime.datetime(2020, 1, 2, 3)], lambda pa: 
pa.list_(pa.timestamp("us"))),
+    # Decimals of a list take the smallest precision and scale that hold them, 
as PySpark does.
+    ([decimal.Decimal("1.5"), decimal.Decimal("10.25")],
+     lambda pa: pa.list_(pa.decimal128(4, 2))),
+    # A dict cell is a struct of the value types of its keys, mixed or not, 
not a map.
+    ({"u": 1, "v": "a"}, lambda pa: pa.struct([("u", pa.int64()), ("v", 
pa.string())])),
+    ({"u": 1, "v": 2}, lambda pa: pa.struct([("u", pa.int64()), ("v", 
pa.int64())])),
+])
+def test_multi_and_categorical_labels_convert_cells_as_pyspark(
+    mock_connect, labels, cell, arrow_type
+):
+    # A plain frame whose labels are a MultiIndex or a CategoricalIndex 
converts with Arrow,
+    # as one with default labels: its cells take the types that PySpark 
infers, and not the
+    # ones of the row path (a timestamp in the session time zone, a map, or an 
error).
+    import pyarrow as pa
+
+    pd = pytest.importorskip("pandas")
+    columns = {
+        "multi2": pd.MultiIndex.from_tuples([("a", "x")]),
+        "multi3": pd.MultiIndex.from_tuples([("a", "x", "p")]),
+        "categorical": pd.CategoricalIndex(["a"]),
+    }[labels]
+    data = pd.DataFrame([[cell]], columns=columns, dtype=object)
+    table = _native_number_input_table(mock_connect, data)
+    assert table.num_columns == 1
+    assert table.schema.field(0).type == arrow_type(pa)
+    assert table.column(0).to_pylist() == [cell]
+
+
 def test_create_dataframe_pandas_errors_as_pyspark():
     pd = pytest.importorskip("pandas")
     from pyspark.errors import PySparkTypeError, PySparkValueError


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to