Coverage for src/pyhiperta/utils/nanify.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v7.15.3, created at 2026-08-07 14:41 +0000

1# Copyright 2026 CNRS 

2# This software is distributed under the terms of the CeCILL-C free software license. 

3 

4"""Transform values to NaN.""" 

5 

6import numpy as np 

7 

8 

9def nanify(a, condition): 

10 """Set a or values of a to np.nan where `condition` is true. 

11 

12 `a` can either be a number, then `nanify` returns np.nan if condition is true, or an array, 

13 in which case `nanify` returns the array with the values where condition is true set to np.nan. 

14 This function main purpose is to provide a convinient way to perform `a[condition] = np.nan` 

15 even when `a` is a single number and not an array. 

16 

17 Parameters 

18 ---------- 

19 a : np.scalar or np.ndarray 

20 The value to convert to np.nan is condition is true. 

21 condition : bool or np.ndarray 

22 The boolean(s) controlling where to set values to np.nan. If an array it typically is a 

23 numpy condition array, see examples. 

24 

25 Returns 

26 ------- 

27 np.nan if a is a scalar, otherwise `a` after `a[condition] = np.nan`. 

28 

29 Examples 

30 -------- 

31 >>> a = 12 

32 >>> nanify(a, a < 13) 

33 np.float32(nan) 

34 >>> a = np.array([1.0, 2.0, 3.0]) 

35 >>> nanify(a, a < 2) 

36 array([nan, 2., 3.]) 

37 """ 

38 if np.isscalar(a): 

39 if condition: 

40 return np.float32(np.nan) # this is subscriptable, while np.nan[..., np.newaxis] raises an exception! 

41 return a 

42 a[condition] = np.nan 

43 return a