Skip to content
Open
Changes from all commits
Commits
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
77 changes: 77 additions & 0 deletions python/pyarrow/tests/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -2267,6 +2267,83 @@ def test_identity_cast_dates(value_type):
assert pc.cast(arr, value_type) == arr


def test_struct_cast_null_field():
# GH-35408
arr = pa.array([{'a': 1, 'b': None}, {'a': 2, 'b': None}])
assert arr.type == pa.struct([('a', pa.int64()), ('b', pa.null())])

target = pa.struct([('a', pa.int64()), ('b', pa.int64())])
result = arr.cast(target)
result.validate(full=True)
assert result.type == target
assert result.to_pylist() == [{'a': 1, 'b': None}, {'a': 2, 'b': None}]


def test_struct_cast_field_types():
arr = pa.array(
[{'a': 1, 'b': 'x'}, None, {'a': 3, 'b': None}],
type=pa.struct([('a', pa.int32()), ('b', pa.string())]))

target = pa.struct([('a', pa.int64()), ('b', pa.large_string())])
result = arr.cast(target)
result.validate(full=True)
assert result.type == target
assert result.to_pylist() == arr.to_pylist()


def test_struct_cast_reorder_subset_and_missing_fields():
arr = pa.array(
[{'a': 1, 'b': 'x'}, None, {'a': 3, 'b': None}],
type=pa.struct([('a', pa.int32()), ('b', pa.string())]))

# Fields are matched by name, so reordering keeps the values.
target = pa.struct([('b', pa.string()), ('a', pa.int32())])
result = arr.cast(target)
result.validate(full=True)
assert result.to_pylist() == [
{'b': 'x', 'a': 1}, None, {'b': None, 'a': 3}]

# Dropping a field.
target = pa.struct([('a', pa.int32())])
result = arr.cast(target)
result.validate(full=True)
assert result.to_pylist() == [{'a': 1}, None, {'a': 3}]

# A field absent from the source is filled with nulls.
target = pa.struct([('a', pa.int32()), ('c', pa.int8())])
result = arr.cast(target)
result.validate(full=True)
assert result.to_pylist() == [
{'a': 1, 'c': None}, None, {'a': 3, 'c': None}]


def test_struct_cast_nullability():
arr = pa.array(
[{'a': 1, 'b': 'x'}, None, {'a': 3, 'b': None}],
type=pa.struct([('a', pa.int32()), ('b', pa.string())]))

target = pa.struct([pa.field('a', pa.int32(), nullable=False),
pa.field('b', pa.string())])
result = arr.cast(target)
result.validate(full=True)
assert result.type == target
assert result.to_pylist() == arr.to_pylist()


def test_struct_cast_nested():
arr = pa.array(
[{'p': {'a': 1, 'b': 2.5}}],
type=pa.struct([('p', pa.struct([('a', pa.int8()),
('b', pa.float32())]))]))

target = pa.struct([('p', pa.struct([('b', pa.float64()),
('a', pa.int64())]))])
result = arr.cast(target)
result.validate(full=True)
assert result.type == target
assert result.to_pylist() == [{'p': {'b': 2.5, 'a': 1}}]


@pytest.mark.parametrize('value_type', numerical_arrow_types)
def test_fsl_to_fsl_cast(value_type):
# Different field name and different type.
Expand Down