Skip to content

Commit

Permalink
ARROW-16651 : [Python] Casting Table to new schema ignores nullabilit…
Browse files Browse the repository at this point in the history
…y of fields (apache#14048)

```python
table = pa.table({'a': [None, 1], 'b': [None, True]})
new_schema = pa.schema([pa.field("a", "int64", nullable=True), pa.field("b", "bool", nullable=False)])
casted = table.cast(new_schema)

```

Now leads to
```
RuntimeError: Casting field 'b' with null values to non-nullable
```

Authored-by: kshitij12345 <kshitijkalambarkar@gmail.com>
Signed-off-by: Joris Van den Bossche <jorisvandenbossche@gmail.com>
  • Loading branch information
kshitij12345 authored and fatemehp committed Oct 17, 2022
1 parent 3c48e0d commit 9ae2dbe
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions python/pyarrow/table.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -3401,6 +3401,9 @@ cdef class Table(_PandasConvertible):
.format(self.schema.names, target_schema.names))

for column, field in zip(self.itercolumns(), target_schema):
if not field.nullable and column.null_count > 0:
raise ValueError("Casting field {!r} with null values to non-nullable"
.format(field.name))
casted = column.cast(field.type, safe=safe, options=options)
newcols.append(casted)

Expand Down
12 changes: 12 additions & 0 deletions python/pyarrow/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,3 +2192,15 @@ def test_table_join_many_columns():
"col6": ["A", "B", None, "Z"],
"col7": ["A", "B", None, "Z"],
})


def test_table_cast_invalid():
# Casting a nullable field to non-nullable should be invalid!
table = pa.table({'a': [None, 1], 'b': [None, True]})
new_schema = pa.schema([pa.field("a", "int64", nullable=True),
pa.field("b", "bool", nullable=False)])
with pytest.raises(ValueError):
table.cast(new_schema)

table = pa.table({'a': [None, 1], 'b': [False, True]})
assert table.cast(new_schema).schema == new_schema

0 comments on commit 9ae2dbe

Please sign in to comment.