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 90839fa1 [SPARK-61351][CONNECT][PYTHON] Convert pandas frames with
nullable or Arrow-backed column labels through Arrow, as PySpark does
90839fa1 is described below
commit 90839fa1766a27f7af4dcbb1d6d462707e2c0a7c
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:36:44 2026 +0900
[SPARK-61351][CONNECT][PYTHON] Convert pandas frames with nullable or
Arrow-backed column labels through Arrow, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61351](https://issues.apache.org/jira/browse/SPARK-61351): a pandas
frame with nullable or Arrow-backed column labels is converted through Arrow,
as PySpark converts it.
- In `python/pyspark/sql/_pandas_input.py`, the new
`_has_canonical_label_array` accepts more storages of an exact label `Index` on
the Arrow routes of `createDataFrame`:
- pandas' masked arrays: IntegerArray, FloatingArray and BooleanArray,
over ndarrays `_data` and `_mask`;
- the ArrowExtensionArray of any Arrow type, over a ChunkedArray
`_pa_array`.
- This follows SPARK-61314, which did the same for DatetimeIndex,
TimedeltaIndex, PeriodIndex and IntervalIndex labels.
- As for the string labels, the check makes sure reading the labels runs no
user code:
- the class must be pandas' own;
- each hook that reading the labels reaches (`__iter__`, `__getitem__`,
`__len__`, `__array__`, `__contains__`, `to_numpy`, `astype`, `isna`, `tolist`,
`fillna`, `_hasna`, `dtype`) must be a function of pandas' own array modules,
or the getter of a property or `cache_readonly`;
- no instance attribute may shadow these hooks.
- The existing recursion then covers MultiIndex levels and CategoricalIndex
categories of these kinds. Sparse labels keep the row path.
### Why are the changes needed?
Such labels come from a pivot, unstack or `.T` of nullable
(`convert_dtypes()`) or Arrow-backed (`dtype_backend="pyarrow"`) data. These
frames took the native row path, whose cells convert differently from PySpark
4.3.0's Arrow conversion:
| Cell | Drop-in (row path) | PySpark |
|---|---|---|
| object column `[1, 2.5]` | "Type mismatch in row data" | double |
| dict | map | struct |
| NaN in a list | NaN | None |
| `np.int32` | bigint | int |
| `Decimal` in a list | `decimal(38,1)` | `decimal(2,1)` |
| naive datetime | timestamp | timestamp_ntz |
Also, under `spark.sql.session.timeZone=Asia/Seoul` with a client in
Asia/Seoul, a datetime64 column under an Int64 label with an explicit
`timestamp_ntz` schema read back `2020-01-01 18:00`; PySpark reads `2020-01-02
03:00`.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client: these frames convert as in PySpark.
### How was this patch tested?
- Offline (`python/tests/test_dropin_offline.py`), next to the
datetime-like label tests of SPARK-61314:
- `test_nullable_and_arrow_labels_convert_cells_as_pyspark` has 35 cases.
It covers Int64, Float64, boolean, `int64[pyarrow]` and `timestamp[pyarrow]`
labels, a MultiIndex level and a CategoricalIndex of Int64. Each runs with the
mixed int/float, naive datetime list, dict, NaN-in-list and `np.int32` cells,
and gets PySpark's Arrow types and values. All fail without the change.
- `test_label_arrays_with_a_hook_of_their_own_keep_the_row_path`: a label
array whose instance shadows a hook keeps the row path.
- Live (`python/tests/test_dropin_e2e.py`):
`test_create_dataframe_of_nullable_labels_keeps_ntz_values_as_pyspark`, for the
NTZ case above. It fails without the change.
- The reviewer's probe against official PySpark 4.3.0 (TZ=Asia/Seoul):
- before the change, 240 differing lines over 7 label kinds;
- after it, only the 34 lines of Sparse labels, which keep the row path.
- The pandas internals the check reads were checked in pandas 2.3.3
(installed) and in the pandas 3.1.0 sources. CI's coverage job installs pandas
3.1: the hooks are in the same modules, and `cache_readonly` has `fget`.
- The offline Python suites and the live drop-in suites against a local
Spark 4.3.0 server pass. 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 #464 from HyukjinKwon/s16-pandas-label-arrays.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
python/pyspark/sql/_pandas_input.py | 59 +++++++++++++++++++++++++++++++++++
python/tests/test_dropin_e2e.py | 26 ++++++++++++++++
python/tests/test_dropin_offline.py | 62 +++++++++++++++++++++++++++++++++++++
3 files changed, 147 insertions(+)
diff --git a/python/pyspark/sql/_pandas_input.py
b/python/pyspark/sql/_pandas_input.py
index f17eee41..69b66839 100644
--- a/python/pyspark/sql/_pandas_input.py
+++ b/python/pyspark/sql/_pandas_input.py
@@ -299,6 +299,62 @@ def _has_canonical_interval_array(backing, module, name):
return True
+# The hooks of a label array that iterating, measuring and converting the
labels of an Index
+# reach, in pandas 2 and 3.
+_LABEL_ARRAY_HOOKS = ("__iter__", "__getitem__", "__len__", "__array__",
"__contains__",
+ "to_numpy", "astype", "isna", "tolist", "fillna",
"_hasna", "dtype")
+
+
+def _has_canonical_label_array(backing, pa):
+ """Accept the exact masked or Arrow storage of an Index of labels.
+
+ pandas' nullable labels (Int64, Float64 or boolean, as a pivot or `.T` of
`convert_dtypes()`
+ data has them) are an IntegerArray, FloatingArray or BooleanArray over the
ndarrays `_data`
+ and `_mask`, and Arrow-backed labels of any type
(`dtype_backend="pyarrow"`) are an
+ ArrowExtensionArray over the ChunkedArray `_pa_array`. As for the string
labels, the class
+ must be pandas' own, and every hook that reading the labels reaches must
be a function (or
+ the getter of a property or a cached property) of pandas' own array
modules, shadowed by no
+ instance attribute, so that reading the labels runs no user code.
+ """
+ import numpy as np
+
+ try:
+ from pandas.core.arrays import base as base_module, boolean as
boolean_module
+ from pandas.core.arrays import floating as floating_module, integer as
integer_module
+ from pandas.core.arrays import masked as masked_module, numeric as
numeric_module
+ from pandas.core.arrays.arrow import array as arrow_module
+ from pandas._libs.properties import CachedProperty
+ except ImportError:
+ return False
+ cls = type(backing)
+ masked = (vars(integer_module).get("IntegerArray"),
vars(floating_module).get("FloatingArray"),
+ vars(boolean_module).get("BooleanArray"))
+ if any(cls is candidate for candidate in masked if candidate is not None):
+ data, mask = vars(backing).get("_data"), vars(backing).get("_mask")
+ if (type(data) is not np.ndarray or type(mask) is not np.ndarray
+ or mask.dtype != np.bool_):
+ return False
+ modules = (masked_module, numeric_module, boolean_module,
integer_module,
+ floating_module, base_module)
+ elif pa is not None and cls is
vars(arrow_module).get("ArrowExtensionArray"):
+ if type(vars(backing).get("_pa_array")) is not pa.ChunkedArray:
+ return False
+ modules = (arrow_module, base_module)
+ else:
+ return False
+ if _raw_class_attribute(cls, "__getattribute__")[1] is not
object.__getattribute__:
+ return False
+ for name in _LABEL_ARRAY_HOOKS:
+ if name in vars(backing):
+ return False
+ hook = _raw_class_attribute(cls, name)[1]
+ if type(hook) is property or type(hook) is CachedProperty:
+ hook = hook.fget
+ if not _defined_in(hook, name, *modules):
+ return False
+ return True
+
+
def _has_canonical_columns(columns):
"""Decline label containers whose row-path iteration can run custom
hooks."""
import sys
@@ -368,6 +424,9 @@ def _has_canonical_columns(columns):
backing = vars(columns).get("_data")
if type(backing) is np.ndarray:
return True
+ # Nullable and Arrow-backed labels of other types than strings take the
Arrow routes too.
+ if _has_canonical_label_array(backing, sys.modules.get("pyarrow")):
+ return True
# Arrow-backed labels already hold PyArrow storage. Do not import optional
# Arrow modules just to decide whether a fallback input is eligible.
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e05d5a4a..f7404170 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1660,6 +1660,32 @@ def
test_create_dataframe_of_datetime_labels_keeps_ntz_values_as_pyspark(session
time.tzset()
+def
test_create_dataframe_of_nullable_labels_keeps_ntz_values_as_pyspark(session):
+ # As PySpark's, as for the datetime labels above: a datetime64 column
under an Int64 label (a
+ # pivot of `convert_dtypes()` data) reads back unchanged with an explicit
timestamp_ntz, not
+ # shifted by the time zone of the session or of the client, set to
Asia/Seoul here.
+ import pandas as pd
+
+ frame = pd.DataFrame({"x": pd.Series(pd.to_datetime(["2020-01-02 03:00",
None]))})
+ frame.columns = pd.Index(pd.array([1], dtype="Int64"))
+ 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 d56187b4..2cbb63ff 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9332,6 +9332,68 @@ def test_datetimelike_labels_convert_cells_as_pyspark(
assert table.column(0).to_pylist() == values
[email protected]("labels", [
+ "Int64", "Float64", "boolean", "int64[pyarrow]", "timestamp[pyarrow]",
"multi_Int64",
+ "categorical_Int64"])
[email protected]("cells, arrow_type, values", [
+ ("int_float", lambda pa: pa.float64(), [1.0, 2.5]),
+ ("naive_list", lambda pa: pa.list_(pa.timestamp("us")),
+ [[datetime.datetime(2020, 1, 2, 3)], None]),
+ ("dict", lambda pa: pa.struct([("u", pa.int64()), ("v", pa.string())]),
+ [{"u": 1, "v": "a"}, None]),
+ ("nan_list", lambda pa: pa.list_(pa.float64()), [[1.0, None], None]),
+ ("np_int32", lambda pa: pa.int32(), [1, 2]),
+])
+def test_nullable_and_arrow_labels_convert_cells_as_pyspark(
+ mock_connect, labels, cells, arrow_type, values
+):
+ # A plain frame whose labels are an Index of pandas' nullable or Arrow
dtypes (a pivot or `.T`
+ # of `convert_dtypes()` or Arrow-backed data), or a MultiIndex level or
CategoricalIndex of
+ # them, converts with Arrow as one with default labels: its cells take the
types that PySpark
+ # infers, as for the datetime-like labels above.
+ 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 = {
+ "Int64": pd.Index(pd.array([1], dtype="Int64")),
+ "Float64": pd.Index(pd.array([1.5], dtype="Float64")),
+ "boolean": pd.Index(pd.array([True], dtype="boolean")),
+ "int64[pyarrow]": pd.Index(pd.array([1], dtype="int64[pyarrow]")),
+ "timestamp[pyarrow]": pd.Index(pd.array([pd.Timestamp("2020-01-01")],
+
dtype="timestamp[us][pyarrow]")),
+ "multi_Int64": pd.MultiIndex.from_arrays([pd.array([1],
dtype="Int64"), ["x"]]),
+ "categorical_Int64": pd.CategoricalIndex(pd.array([1], dtype="Int64")),
+ }[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_label_arrays_with_a_hook_of_their_own_keep_the_row_path():
+ # The labels of the Arrow routes run no user code: a nullable or Arrow
label array whose
+ # instance shadows a hook that reading the labels reaches keeps the native
row path.
+ pd = pytest.importorskip("pandas")
+ pytest.importorskip("pyarrow")
+ from pyspark.sql._pandas_input import _has_canonical_columns
+
+ for dtype in ("Int64", "boolean", "int64[pyarrow]"):
+ index = pd.Index(pd.array([1, 0], dtype=dtype))
+ assert _has_canonical_columns(index), dtype
+ vars(index)["_data"].__dict__["__iter__"] = lambda: iter(["shadowed"])
+ assert not _has_canonical_columns(index), dtype
+
+
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]