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 7ba882dd [SPARK-61314][CONNECT][PYTHON] Convert pandas frames with 
DatetimeIndex, TimedeltaIndex, PeriodIndex or IntervalIndex labels through 
Arrow, as PySpark does
7ba882dd is described below

commit 7ba882dd918b8c0d44de221f9f6fa5e1a242ed1b
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 08:53:28 2026 +0900

    [SPARK-61314][CONNECT][PYTHON] Convert pandas frames with DatetimeIndex, 
TimedeltaIndex, PeriodIndex or IntervalIndex labels through Arrow, as PySpark 
does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61314](https://issues.apache.org/jira/browse/SPARK-61314): Convert 
pandas frames with DatetimeIndex, TimedeltaIndex, PeriodIndex or IntervalIndex 
labels through Arrow, as PySpark does.
    
    - A pandas frame whose column labels are an exact `DatetimeIndex`, 
`TimedeltaIndex`, `PeriodIndex` or `IntervalIndex` now takes the Arrow routes 
of `createDataFrame` (inferred schema, names, or explicit schema), as frames 
with str labels, a default `RangeIndex`, or a plain 
`MultiIndex`/`CategoricalIndex` already do. The check is 
`_has_canonical_columns` in `python/pyspark/sql/_pandas_input.py`. It accepts 
these labels with the override rules of an `Index` (the exact class, no 
override [...]
    - MultiIndex levels and CategoricalIndex categories recurse through the 
same check, so a MultiIndex with a `DatetimeIndex` level now takes the Arrow 
routes too. The comment that a DatetimeIndex level keeps the row path is 
removed.
    - Subclasses, instance overrides and label containers whose storage is not 
pandas' own keep the row path, as before.
    - Official PySpark 4.3.0 names such columns by `str` of the label 
(`2020-01-01 00:00:00`, `(0, 1]`, `(Timestamp('2020-01-01 00:00:00'), 'x')`), 
which the Arrow routes already do. Its cell types are the Arrow types of the 
frame: a mixed int/float column is `double`, a naive datetime list is 
`array<timestamp_ntz>`, a dict is a `struct`, a NaN in a list is `null`, and a 
NumPy `int32` is `int`. The row path gave `Type mismatch in row data`, a 
`timestamp` shifted by the client's local offs [...]
    
    ### Why are the changes needed?
    
    A pandas frame with such labels converted its cells on the native row path, 
which differs from PySpark. For example, with 
`spark.sql.session.timeZone=Asia/Seoul` and a client whose local zone is 
Asia/Seoul:
    
    ```python
    pdf = pd.DataFrame({"x": pd.Series(pd.to_datetime(["2020-01-02 03:00", 
None]))})
    pdf.columns = pd.DatetimeIndex(["2020-01-01"])
    spark.createDataFrame(pdf, "p timestamp_ntz").collect()
    # ours: datetime(2020, 1, 1, 18, 0); PySpark 4.3.0: datetime(2020, 1, 2, 3, 
0)
    ```
    
    The shift follows the client's local zone, not the session zone: it 
happened for every non-UTC client zone tried (Asia/Seoul and 
America/Los_Angeles, with either session zone), and not with a UTC client. The 
same frame under a str label gave the official value. Other cases: `[1, 2.5]` 
in an object column (`PySparkRuntimeError: Type mismatch in row data`, PySpark: 
`double`), `{"u": 1, "v": 2}` (a `map`, PySpark: `struct<u:bigint,v:bigint>`), 
`np.int32` cells (`bigint`, PySpark: `int`), [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Pandas frames whose labels are exact DatetimeIndex, TimedeltaIndex, 
PeriodIndex or IntervalIndex objects (and MultiIndex/CategoricalIndex labels of 
those) convert their cells as PySpark does: the values of naive datetimes under 
an explicit `timestamp_ntz` are no longer shifted by the client's local zone, 
and the types of mixed numbers, lists, dicts and NumPy scalars match PySpark 
4.3.0. Subclassed frames and labels are unchanged.
    
    ### How was this patch tested?
    
    - `test_datetimelike_labels_convert_cells_as_pyspark` (offline, 25 cases: 
DatetimeIndex, TimedeltaIndex, PeriodIndex, IntervalIndex and a MultiIndex with 
a DatetimeIndex level, each with a mixed int/float column, a naive datetime 
list, a dict, a NaN in a list, and `np.int32` cells): the Arrow type and the 
values of the cells are PySpark's (`double`, `list<timestamp[us]>`, `struct<u: 
int64, v: string>`, `list<double>` with null, `int32`). All 25 fail without 
this change and pass with i [...]
    - `test_create_dataframe_of_datetime_labels_keeps_ntz_values_as_pyspark` 
(live): with `spark.sql.session.timeZone=Asia/Seoul` and the client's local 
zone set to Asia/Seoul (restored afterwards), a datetime64 column under a 
DatetimeIndex label with an explicit `timestamp_ntz` reads back as `2020-01-02 
03:00:00`, as official PySpark 4.3.0 does. It fails without this change 
(`2020-01-01 18:00:00`). The client zone must be set too: under a UTC client 
the row path does not shift.
    - Probes against official PySpark 4.3.0 over the label kinds above (plus 
tz-aware and NaT DatetimeIndex, empty DatetimeIndex, IntervalIndex of 
datetimes, CategoricalIndex of DatetimeIndex, PeriodIndex and IntervalIndex 
categories, MultiIndex levels of TimedeltaIndex, PeriodIndex, IntervalIndex and 
tz-aware DatetimeIndex) across 40+ cell kinds, with no schema, a DDL, and 
names: 0 divergences after this change (1050 and 350 result lines compared); 
the pre-fix code diverged in 145 lines  [...]
    - The offline Python suites (2952 passed, 8 skipped), the new tests also 
under pytest 9.2, and the live drop-in tests `-k pandas` (19 passed) and `-k 
"labels or ntz or empty_arrow_table"` (7 passed) against a local Spark 4.3.0 
server. The pandas internals the check reads were checked against the pandas 
3.1.1 sources, which CI's coverage job installs. 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 #433 from HyukjinKwon/SPARK-61314-pandas-datetimelike-labels.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 python/pyspark/sql/_pandas_input.py | 126 +++++++++++++++++++++++++++++++++++-
 python/tests/test_dropin_e2e.py     |  27 ++++++++
 python/tests/test_dropin_offline.py |  48 ++++++++++++++
 3 files changed, 199 insertions(+), 2 deletions(-)

diff --git a/python/pyspark/sql/_pandas_input.py 
b/python/pyspark/sql/_pandas_input.py
index c2773729..f17eee41 100644
--- a/python/pyspark/sql/_pandas_input.py
+++ b/python/pyspark/sql/_pandas_input.py
@@ -166,7 +166,8 @@ def _has_canonical_structured_columns(columns, module, 
multi):
     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.
+    and categories of a CategoricalIndex. Each label container inside is 
checked as a label
+    index (see `_has_canonical_columns`), so a DatetimeIndex level is checked 
as one too.
     """
     import numpy as np
     from pandas.core import base as base_module
@@ -203,6 +204,101 @@ def _has_canonical_structured_columns(columns, module, 
multi):
     return _has_canonical_columns(categorical.categories.__get__(data))
 
 
+def _has_canonical_label_index(columns, array_check, array_module, array_name):
+    """Accept a plain DatetimeIndex, TimedeltaIndex, PeriodIndex or 
IntervalIndex of labels.
+
+    As for an Index, the labels only name the columns. The override rules of 
an Index apply:
+    the exact class, no override of `__getattribute__`, `__iter__` or 
`__len__` on the class
+    or the instance, pandas' own iteration and values, and no class in the MRO 
that defines
+    the `_data` storage. The storage must pass `array_check`, which takes the 
exact array
+    class `array_name` of `array_module`.
+    """
+    from pandas.core import base as base_module
+    from pandas.core.indexes import base as index_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__", index_module)
+            or any("_data" in vars(base) for base in cls.__mro__)):
+        return False
+    _, values = _raw_class_attribute(cls, "_values")
+    if not _defined_in(getattr(values, "fget", None), "_values", index_module):
+        return False
+    return array_check(vars(columns).get("_data"), array_module, array_name)
+
+
+def _has_canonical_datetimelike_array(backing, module, name):
+    """Accept the exact DatetimeArray, TimedeltaArray or PeriodArray storage 
of a label index.
+
+    Iteration boxes the int64 `_ndarray` through pandas' own `__iter__` and 
`_box_func`, and
+    indexing goes through pandas' own `__getitem__`. No instance may shadow 
those hooks.
+    """
+    import numpy as np
+    from pandas._libs.arrays import NDArrayBacked
+    from pandas.core.arrays import _mixins as mixins_module
+    from pandas.core.arrays import datetimelike as datetimelike_module
+
+    cls = vars(module).get(name)
+    if type(backing) is not cls:
+        return False
+    if cls.__getattribute__ is not object.__getattribute__ or any(
+        hook in vars(backing) for hook in
+        ("__iter__", "__getitem__", "__len__", "__array__", "_box_func", 
"asi8", "_ndarray")
+    ):
+        return False
+    if (not _defined_in(_raw_class_attribute(cls, "__iter__")[1], "__iter__", 
module,
+                        datetimelike_module)
+            or not _defined_in(_raw_class_attribute(cls, "__getitem__")[1], 
"__getitem__",
+                               datetimelike_module, mixins_module)
+            or _raw_class_attribute(cls, "__len__")[1] is not 
NDArrayBacked.__len__
+            or not _defined_in(_raw_class_attribute(cls, "_box_func")[1], 
"_box_func", module)):
+        return False
+    try:
+        storage = object.__getattribute__(backing, "_ndarray")
+    except AttributeError:
+        return False
+    return type(storage) is np.ndarray
+
+
+def _has_canonical_interval_array(backing, module, name):
+    """Accept the exact IntervalArray storage of an IntervalIndex label.
+
+    Iteration boxes `_left` and `_right` through pandas' own `__array__`, 
`isna`, `closed` and
+    `__getitem__`. Each endpoint is a NumPy array or a canonical datetime-like 
array.
+    """
+    import numpy as np
+    from pandas.core.arrays import datetimes as datetimes_module
+    from pandas.core.arrays import timedeltas as timedeltas_module
+    from pandas.core.dtypes.dtypes import IntervalDtype
+
+    cls = vars(module).get(name)
+    if type(backing) is not cls:
+        return False
+    if cls.__getattribute__ is not object.__getattribute__ or any(
+        hook in vars(backing) for hook in
+        ("__iter__", "__len__", "__getitem__", "__array__", "isna", "closed", 
"dtype")
+    ):
+        return False
+    if (not all(_defined_in(_raw_class_attribute(cls, hook)[1], hook, module)
+                for hook in ("__iter__", "__len__", "__getitem__", 
"__array__", "isna"))
+            or not all(_defined_in(getattr(_raw_class_attribute(cls, hook)[1], 
"fget", None),
+                                   hook, module) for hook in ("closed", 
"dtype"))
+            or type(vars(backing).get("_dtype")) is not IntervalDtype):
+        return False
+    for side in ("_left", "_right"):
+        endpoint = vars(backing).get(side)
+        if type(endpoint) is np.ndarray:
+            continue
+        if not (_has_canonical_datetimelike_array(endpoint, datetimes_module, 
"DatetimeArray")
+                or _has_canonical_datetimelike_array(endpoint, 
timedeltas_module,
+                                                     "TimedeltaArray")):
+            return False
+    return True
+
+
 def _has_canonical_columns(columns):
     """Decline label containers whose row-path iteration can run custom 
hooks."""
     import sys
@@ -210,9 +306,18 @@ def _has_canonical_columns(columns):
     import numpy as np
     import pandas as pd
     from pandas.core import base as base_module
+    from pandas.core.arrays import datetimes as datetimes_array_module
+    from pandas.core.arrays import interval as interval_array_module
+    from pandas.core.arrays import period as period_array_module
+    from pandas.core.arrays import timedeltas as timedeltas_array_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 category as category_module
+    from pandas.core.indexes import datetimes as datetimes_module
+    from pandas.core.indexes import interval as interval_module
+    from pandas.core.indexes import multi as multi_module
+    from pandas.core.indexes import period as period_module
     from pandas.core.indexes import range as range_module
+    from pandas.core.indexes import timedeltas as timedeltas_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:
@@ -226,6 +331,23 @@ def _has_canonical_columns(columns):
             and type(columns) is pd.CategoricalIndex):
         return _has_canonical_structured_columns(columns, category_module, 
False)
 
+    # Plain DatetimeIndex, TimedeltaIndex, PeriodIndex and IntervalIndex 
labels (`.T` of a
+    # time-indexed frame, a pivot of datetimes) take the Arrow routes too: 
their values are
+    # pandas' own and only name the columns.
+    if pd.DatetimeIndex is datetimes_module.DatetimeIndex and type(columns) is 
pd.DatetimeIndex:
+        return _has_canonical_label_index(
+            columns, _has_canonical_datetimelike_array, 
datetimes_array_module, "DatetimeArray")
+    if (pd.TimedeltaIndex is timedeltas_module.TimedeltaIndex
+            and type(columns) is pd.TimedeltaIndex):
+        return _has_canonical_label_index(
+            columns, _has_canonical_datetimelike_array, 
timedeltas_array_module, "TimedeltaArray")
+    if pd.PeriodIndex is period_module.PeriodIndex and type(columns) is 
pd.PeriodIndex:
+        return _has_canonical_label_index(
+            columns, _has_canonical_datetimelike_array, period_array_module, 
"PeriodArray")
+    if pd.IntervalIndex is interval_module.IntervalIndex and type(columns) is 
pd.IntervalIndex:
+        return _has_canonical_label_index(
+            columns, _has_canonical_interval_array, interval_array_module, 
"IntervalArray")
+
     Index = index_module.Index
     if (pd.Index is not Index or type(columns) is not Index
             or Index.__getattribute__ is not object.__getattribute__
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index b19656af..58ee4eb3 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1513,6 +1513,33 @@ def 
test_create_dataframe_with_a_schema_edited_in_place(session):
     assert df.collect() == [Row(a=1, b="x", c=2.0)]
 
 
+def 
test_create_dataframe_of_datetime_labels_keeps_ntz_values_as_pyspark(session):
+    # As PySpark's: a datetime64 column under a DatetimeIndex label (`.T` of a 
time-indexed
+    # frame) reads back unchanged with an explicit timestamp_ntz. The naive 
values are not
+    # shifted by a time zone, of the session or of the client's local time, 
which is set to
+    # Asia/Seoul here as well: a client in UTC does not show the shift.
+    import pandas as pd
+
+    frame = pd.DataFrame({"x": pd.Series(pd.to_datetime(["2020-01-02 03:00", 
None]))})
+    frame.columns = pd.DatetimeIndex(["2020-01-01"])
+    previous = session.conf.get("spark.sql.session.timeZone")
+    previous_local = os.environ.get("TZ")
+    session.conf.set("spark.sql.session.timeZone", "Asia/Seoul")
+    os.environ["TZ"] = "Asia/Seoul"
+    time.tzset()
+    try:
+        df = session.createDataFrame(frame, "p timestamp_ntz")
+        assert df.schema.simpleString() == "struct<p:timestamp_ntz>"
+        assert df.collect() == [Row(p=datetime(2020, 1, 2, 3)), Row(p=None)]
+    finally:
+        session.conf.set("spark.sql.session.timeZone", previous)
+        if previous_local is None:
+            os.environ.pop("TZ", None)
+        else:
+            os.environ["TZ"] = previous_local
+        time.tzset()
+
+
 def test_create_dataframe_from_empty_arrow_table(session):
     empty = pa.table({"a": pa.array([], pa.int64()), "b": pa.array([], 
pa.string())})
     df = session.createDataFrame(empty, "a long, b string")
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index ca6d4ce1..1422ba4c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -8867,6 +8867,54 @@ def 
test_create_dataframe_of_a_numpy_array_as_pyspark(mock_connect):
     assert e.value.getCondition() == "CANNOT_INFER_EMPTY_SCHEMA"
 
 
[email protected](
+    "labels", ["datetime", "timedelta", "period", "interval", 
"multi_datetime"])
[email protected]("cells, arrow_type, values", [
+    # A mixed int and float column is a double, as PySpark infers it, not a 
row error.
+    ("int_float", lambda pa: pa.float64(), [1.0, 2.5]),
+    # A naive datetime of a list is a timestamp_ntz, not a time of the session 
time zone.
+    ("naive_list", lambda pa: pa.list_(pa.timestamp("us")),
+     [[datetime.datetime(2020, 1, 2, 3)], None]),
+    # A dict is a struct of the value types of its keys, mixed or not, and not 
a map.
+    ("dict", lambda pa: pa.struct([("u", pa.int64()), ("v", pa.string())]),
+     [{"u": 1, "v": "a"}, None]),
+    # A NaN in a list is a null, as PySpark has it.
+    ("nan_list", lambda pa: pa.list_(pa.float64()), [[1.0, None], None]),
+    # A NumPy int32 is an int, as PySpark infers it.
+    ("np_int32", lambda pa: pa.int32(), [1, 2]),
+])
+def test_datetimelike_labels_convert_cells_as_pyspark(
+    mock_connect, labels, cells, arrow_type, values
+):
+    # A plain frame whose labels are a DatetimeIndex, TimedeltaIndex, 
PeriodIndex or IntervalIndex
+    # (or a MultiIndex with a DatetimeIndex level) converts with Arrow, as one 
with default labels:
+    # its cells take the types that PySpark infers.
+    import numpy as np
+    import pyarrow as pa
+
+    pd = pytest.importorskip("pandas")
+    column = {
+        "int_float": [1, 2.5],
+        "naive_list": [[datetime.datetime(2020, 1, 2, 3)], None],
+        "dict": [{"u": 1, "v": "a"}, None],
+        "nan_list": [[1.0, float("nan")], None],
+        "np_int32": [np.int32(1), np.int32(2)],
+    }[cells]
+    columns = {
+        "datetime": pd.DatetimeIndex(["2020-01-01"]),
+        "timedelta": pd.TimedeltaIndex(["1s"]),
+        "period": pd.period_range("2020-01", periods=1, freq="M"),
+        "interval": pd.interval_range(0, 1),
+        "multi_datetime": 
pd.MultiIndex.from_tuples([(pd.Timestamp("2020-01-01"), "x")]),
+    }[labels]
+    data = pd.DataFrame({0: pd.Series(column, dtype=object)})
+    data.columns = columns
+    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() == values
+
+
 def 
test_catalog_function_class_name_is_none_without_a_class_as_pyspark(mock_connect):
     import pyarrow as pa
 


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

Reply via email to