Skip to content

Commit 2d661a8

Browse files
authored
CLN: simplify mask_missing (#38127)
1 parent ba2ae2f commit 2d661a8

File tree

1 file changed

+22
-34
lines changed

1 file changed

+22
-34
lines changed

pandas/core/missing.py

+22-34
Original file line numberDiff line numberDiff line change
@@ -7,65 +7,53 @@
77
import numpy as np
88

99
from pandas._libs import algos, lib
10-
from pandas._typing import DtypeObj
10+
from pandas._typing import ArrayLike, DtypeObj
1111
from pandas.compat._optional import import_optional_dependency
1212

1313
from pandas.core.dtypes.cast import infer_dtype_from_array
1414
from pandas.core.dtypes.common import (
1515
ensure_float64,
1616
is_integer_dtype,
1717
is_numeric_v_string_like,
18-
is_scalar,
1918
needs_i8_conversion,
2019
)
2120
from pandas.core.dtypes.missing import isna
2221

2322

24-
def mask_missing(arr, values_to_mask):
23+
def mask_missing(arr: ArrayLike, values_to_mask) -> np.ndarray:
2524
"""
2625
Return a masking array of same size/shape as arr
2726
with entries equaling any member of values_to_mask set to True
28-
"""
29-
dtype, values_to_mask = infer_dtype_from_array(values_to_mask)
3027
31-
try:
32-
values_to_mask = np.array(values_to_mask, dtype=dtype)
28+
Parameters
29+
----------
30+
arr : ArrayLike
31+
values_to_mask: list, tuple, or scalar
3332
34-
except Exception:
35-
values_to_mask = np.array(values_to_mask, dtype=object)
33+
Returns
34+
-------
35+
np.ndarray[bool]
36+
"""
37+
# When called from Block.replace/replace_list, values_to_mask is a scalar
38+
# known to be holdable by arr.
39+
# When called from Series._single_replace, values_to_mask is tuple or list
40+
dtype, values_to_mask = infer_dtype_from_array(values_to_mask)
41+
values_to_mask = np.array(values_to_mask, dtype=dtype)
3642

3743
na_mask = isna(values_to_mask)
3844
nonna = values_to_mask[~na_mask]
3945

40-
mask = None
46+
# GH 21977
47+
mask = np.zeros(arr.shape, dtype=bool)
4148
for x in nonna:
42-
if mask is None:
43-
if is_numeric_v_string_like(arr, x):
44-
# GH#29553 prevent numpy deprecation warnings
45-
mask = False
46-
else:
47-
mask = arr == x
48-
49-
# if x is a string and arr is not, then we get False and we must
50-
# expand the mask to size arr.shape
51-
if is_scalar(mask):
52-
mask = np.zeros(arr.shape, dtype=bool)
49+
if is_numeric_v_string_like(arr, x):
50+
# GH#29553 prevent numpy deprecation warnings
51+
pass
5352
else:
54-
if is_numeric_v_string_like(arr, x):
55-
# GH#29553 prevent numpy deprecation warnings
56-
mask |= False
57-
else:
58-
mask |= arr == x
53+
mask |= arr == x
5954

6055
if na_mask.any():
61-
if mask is None:
62-
mask = isna(arr)
63-
else:
64-
mask |= isna(arr)
65-
66-
# GH 21977
67-
if mask is None:
68-
mask = np.zeros(arr.shape, dtype=bool)
56+
mask |= isna(arr)
6957

7058
return mask
7159

0 commit comments

Comments
 (0)