diff --git a/python/pyarrow/src/arrow/python/numpy_to_arrow.cc b/python/pyarrow/src/arrow/python/numpy_to_arrow.cc index d4e859d1c707..ea7df38343d2 100644 --- a/python/pyarrow/src/arrow/python/numpy_to_arrow.cc +++ b/python/pyarrow/src/arrow/python/numpy_to_arrow.cc @@ -578,10 +578,13 @@ Status NumPyConverter::VisitBinary(T* builder) { auto data = reinterpret_cast(PyArray_DATA(arr_)); auto AppendNotNull = [builder, this](const uint8_t* data) { - // This is annoying. NumPy allows strings to have nul-terminators, so - // we must check for them here - const size_t item_size = - strnlen(reinterpret_cast(data), static_cast(itemsize_)); + // NumPy's fixed-width bytes dtype (``S``) zero-pads values shorter than + // the item width. Strip only *trailing* null bytes so that genuine + // interior null bytes are preserved (GH-41388). + size_t item_size = static_cast(itemsize_); + while (item_size > 0 && data[item_size - 1] == 0) { + --item_size; + } return builder->Append(data, static_cast(item_size)); }; diff --git a/python/pyarrow/tests/test_array.py b/python/pyarrow/tests/test_array.py index ca063bc6b695..df4b624eb539 100644 --- a/python/pyarrow/tests/test_array.py +++ b/python/pyarrow/tests/test_array.py @@ -3894,6 +3894,42 @@ def test_binary_array_strided(): assert [b"ab", b"ef"] == arrow_array.to_pylist() +@pytest.mark.numpy +def test_binary_array_from_numpy_preserves_interior_nulls(): + # GH-41388: numpy fixed-width bytes arrays with interior '\x00' bytes + # used to be truncated at the first null. NumPy only pads *trailing* + # bytes, so only trailing nulls should be stripped. + values = [b'contains \x00 interior', b'no nulls here'] + np_array = np.array(values) # dtype='S20' + + # Variable-length binary + arr = pa.array(np_array, type=pa.binary()) + assert arr.to_pylist() == values + + # Large binary uses the same converter path + arr_large = pa.array(np_array, type=pa.large_binary()) + assert arr_large.to_pylist() == values + + # Trailing padding on short values is still stripped (NumPy 'S' semantics) + short = np.array([b'short', b'exactlyten']) # dtype='S10' + arr_short = pa.array(short, type=pa.binary()) + assert arr_short.to_pylist() == [b'short', b'exactlyten'] + + # Table.from_pydict goes through the same path + table = pa.Table.from_pydict({'x': np_array}) + assert table['x'].to_pylist() == values + + # Masked variant still preserves interior nulls + masked = pa.array(np_array, type=pa.binary(), + mask=np.array([False, False])) + assert masked.to_pylist() == values + + # Strided variant still preserves interior nulls + stride = np.array([b'one \x00 one', b'two \x00 two', b'three']) + strided = pa.array(stride[::2], type=pa.binary()) + assert strided.to_pylist() == [b'one \x00 one', b'three'] + + @pytest.mark.numpy def test_array_invalid_mask_raises(): # ARROW-10742