Skip to content
Closed
Show file tree
Hide file tree
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
5 changes: 4 additions & 1 deletion python/pyarrow/array.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,8 @@ def _normalize_slice(object arrow_obj, slice key):
indices = np.arange(start, stop, step)
return arrow_obj.take(indices)
else:
return arrow_obj.slice(start, stop - start)
length = max(stop - start, 0)
return arrow_obj.slice(start, length)


cdef Py_ssize_t _normalize_index(Py_ssize_t index,
Expand Down Expand Up @@ -1103,6 +1104,8 @@ cdef class Array(_PandasConvertible):
if length is None:
result = self.ap.Slice(offset)
else:
if length < 0:
raise ValueError('Length must be non-negative')
result = self.ap.Slice(offset, length)

return pyarrow_wrap_array(result)
Expand Down
9 changes: 8 additions & 1 deletion python/pyarrow/tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,9 @@ def test_array_slice():
with pytest.raises(IndexError):
arr.slice(-1)

with pytest.raises(ValueError):
arr.slice(2, -1)

# Test slice notation
assert arr[2:].equals(arr.slice(2))
assert arr[2:5].equals(arr.slice(2, 3))
Expand All @@ -421,7 +424,11 @@ def test_array_slice():
n = len(arr)
for start in range(-n * 2, n * 2):
for stop in range(-n * 2, n * 2):
assert arr[start:stop].to_pylist() == arr.to_pylist()[start:stop]
res = arr[start:stop]
res.validate()
expected = arr.to_pylist()[start:stop]
assert res.to_pylist() == expected
assert res.to_numpy().tolist() == expected


def test_array_slice_negative_step():
Expand Down