Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ARROW-16651 : [Python] Casting Table to new schema ignores nullability of fields #14048

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
7 changes: 6 additions & 1 deletion python/pyarrow/table.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -3395,11 +3395,16 @@ cdef class Table(_PandasConvertible):
Field field
list newcols = []

if self.schema.names != target_schema.names:
field_names = self.schema.names
if field_names != target_schema.names:
raise ValueError("Target schema's field names are not matching "
"the table's field names: {!r}, {!r}"
.format(self.schema.names, target_schema.names))

for name in field_names:
if self.schema.field(name).nullable and not target_schema.field(name).nullable:
raise RuntimeError(
"Casting a nullable field {!r} to non-nullable".format(name))
for column, field in zip(self.itercolumns(), target_schema):
casted = column.cast(field.type, safe=safe, options=options)
newcols.append(casted)
Expand Down
9 changes: 9 additions & 0 deletions python/pyarrow/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,3 +2192,12 @@ 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(RuntimeError):
table.cast(new_schema)