Skip to content

Commit e38aed5

Browse files
authored
Add scalar support to where (#679)
1 parent 2ad6569 commit e38aed5

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

cubed/array_api/searching_functions.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,5 +88,13 @@ def _searchsorted(x, y, side):
8888

8989

9090
def where(condition, x1, x2, /):
91+
x1_is_scalar = isinstance(x1, (int, float, complex, bool))
92+
x2_is_scalar = isinstance(x2, (int, float, complex, bool))
93+
if x1_is_scalar and x2_is_scalar:
94+
raise TypeError("At least one of x1 and x2 must be an array in where")
95+
elif x1_is_scalar:
96+
x1 = x2._promote_scalar(x1)
97+
elif x2_is_scalar:
98+
x2 = x1._promote_scalar(x2)
9199
dtype = result_type(x1, x2)
92100
return elemwise(nxp.where, condition, x1, x2, dtype=dtype)

cubed/tests/test_array_api.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,22 @@ def test_searchsorted_sorter_not_implemented():
794794
xp.searchsorted(xp.asarray([1, 0]), xp.asarray([1]), sorter=xp.asarray([1, 0]))
795795

796796

797+
def test_where_scalars():
798+
condition = xp.asarray(
799+
[[True, False, True], [False, True, False], [True, False, True]], chunks=(2, 2)
800+
)
801+
a = xp.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], chunks=(2, 2))
802+
803+
b = xp.where(condition, a, 0)
804+
assert_array_equal(b.compute(), np.array([[1, 0, 3], [0, 5, 0], [7, 0, 9]]))
805+
806+
c = xp.where(condition, 0, a)
807+
assert_array_equal(c.compute(), np.array([[0, 2, 0], [4, 0, 6], [0, 8, 0]]))
808+
809+
with pytest.raises(TypeError):
810+
xp.where(condition, 0, 1)
811+
812+
797813
# Statistical functions
798814

799815

0 commit comments

Comments
 (0)