Skip to content

Commit 4dda548

Browse files
authored
fix: Type conversion from Spark Struct to narwhals Struct. (#2037)
* Fixed conversion between Spark Struct type to narwhals Struct type. * Updated test * Addressed PR comment
1 parent 0d406e4 commit 4dda548

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

narwhals/_spark_like/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,12 @@ def native_to_narwhals_dtype(
6464
return dtypes.Struct(
6565
fields=[
6666
dtypes.Field(
67-
name=name,
67+
name=field.name,
6868
dtype=native_to_narwhals_dtype(
69-
dtype[name], version=version, spark_types=spark_types
69+
field.dataType, version=version, spark_types=spark_types
7070
),
7171
)
72-
for name in dtype.fieldNames()
72+
for field in dtype
7373
]
7474
)
7575
return dtypes.Unknown()

tests/expr_and_series/cast_test.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -260,14 +260,20 @@ def test_cast_struct(request: pytest.FixtureRequest, constructor: Constructor) -
260260
native_df = native_df.withColumn( # type: ignore[union-attr]
261261
"a",
262262
F.struct(
263-
F.col("a.movie ").alias("movie ").cast(T.StringType()),
264-
F.col("a.rating").alias("rating").cast(T.DoubleType()),
263+
F.col("a.movie ").cast(T.StringType()).alias("movie "),
264+
F.col("a.rating").cast(T.DoubleType()).alias("rating"),
265265
),
266266
)
267+
assert nw.from_native(native_df).schema == nw.Schema(
268+
{
269+
"a": nw.Struct(
270+
[nw.Field("movie ", nw.String()), nw.Field("rating", nw.Float64())]
271+
)
272+
}
273+
)
267274

268-
dtype = nw.Struct([nw.Field("movie ", nw.String()), nw.Field("rating", nw.Float64())])
275+
dtype = nw.Struct([nw.Field("movie ", nw.String()), nw.Field("rating", nw.Float32())])
269276
result = nw.from_native(native_df).select(nw.col("a").cast(dtype)).lazy().collect()
270-
271277
assert result.schema == {"a": dtype}
272278

273279

0 commit comments

Comments
 (0)