Skip to content

Commit 5b75e4b

Browse files
authored
Merge pull request #44 from peytondmurray/pyarray-arrfunc-nonzero
Add support for `PyArray_NonzeroFunc`
2 parents b15e80a + 7e3d0a1 commit 5b75e4b

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

stringdtype/stringdtype/src/dtype.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,14 @@ stringdtype_getitem(StringDTypeObject *NPY_UNUSED(descr), char **dataptr)
168168
return res;
169169
}
170170

171+
// PyArray_NonzeroFunc
172+
// Unicode strings are nonzero if their length is nonzero.
173+
npy_bool
174+
nonzero(void *data, void *NPY_UNUSED(arr))
175+
{
176+
return ((ss *)data)->len != 0;
177+
}
178+
171179
// Implementation of PyArray_CompareFunc.
172180
// Compares unicode strings by their code points.
173181
int
@@ -225,6 +233,7 @@ static PyType_Slot StringDType_Slots[] = {
225233
{NPY_DT_getitem, &stringdtype_getitem},
226234
{NPY_DT_ensure_canonical, &stringdtype_ensure_canonical},
227235
{NPY_DT_PyArray_ArrFuncs_compare, &compare_strings},
236+
{NPY_DT_PyArray_ArrFuncs_nonzero, &nonzero},
228237
{NPY_DT_get_clear_loop, &stringdtype_get_clear_loop},
229238
{0, NULL}};
230239

stringdtype/tests/test_stringdtype.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,20 @@ def test_sort(strings):
183183
np.testing.assert_array_equal(arr, arr_sorted)
184184

185185

186+
@pytest.mark.parametrize(
187+
"strings",
188+
[
189+
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
190+
["A¢☃€ 😊", "", " ", " "],
191+
["", "a", "😸", "ááðfáíóåéë"],
192+
],
193+
)
194+
def test_nonzero(strings):
195+
arr = np.array(strings, dtype=StringDType())
196+
is_nonzero = np.array([i for i, item in enumerate(arr) if len(item) != 0])
197+
np.testing.assert_array_equal(arr.nonzero()[0], is_nonzero)
198+
199+
186200
def test_creation_functions():
187201
np.testing.assert_array_equal(
188202
np.zeros(3, dtype=StringDType()), ["", "", ""]

0 commit comments

Comments
 (0)