4 examples of 'pandas replace nan with 0' in Python

Every line of 'pandas replace nan with 0' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
135def replace_nan(value, default=0):
136 if math.isnan(value):
137 return default
138 return value

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

36def _replace_nan(a, val):
37 """
38 If `a` is of inexact type, make a copy of `a`, replace NaNs with
39 the `val` value, and return the copy together with a boolean mask
40 marking the locations where NaNs were present. If `a` is not of
41 inexact type, do nothing and return `a` together with a mask of None.
43 Note that scalars will end up as array scalars, which is important
44 for using the result as the value of the out argument in some
45 operations.
47 Parameters
48 ----------
49 a : array-like
50 Input array.
51 val : float
52 NaN values are set to val before doing the operation.
54 Returns
55 -------
56 y : ndarray
57 If `a` is of inexact type, return a copy of `a` with the NaNs
58 replaced by the fill value, otherwise return `a`.
59 mask: {bool, None}
60 If `a` is of inexact type, return a boolean mask marking locations of
61 NaNs, otherwise return None.
63 """
64 a = np.array(a, subok=True, copy=True)
66 if a.dtype == np.object_:
67 # object arrays do not support `isnan` (gh-9009), so make a guess
68 mask = a != a
69 elif issubclass(a.dtype.type, np.inexact):
70 mask = np.isnan(a)
71 else:
72 mask = None
74 if mask is not None:
75 np.copyto(a, val, where=mask)
77 return a, mask
24def fix_nans(mat):
25 """
26 returns the matrix with average over models if a model, sample, chromosome had nan in it.
27 :param mat: ndarray (model, sample, chromosome)
28 :return: mat ndarray (model, sample, chromosome)
29 """
30 mat = np.nan_to_num(mat)
31 idx, idy, idz = np.where(mat == 0)
32 for x, y, z in zip(idx, idy, idz):
33 mat[x, y, z] = mat[:, y, z].mean()
34 return mat
74def filter_nan2none(value):
75 """Convert the NaN value to None, leaving everything else unchanged.
77 This function is meant to be used as a Django template filter. It
78 is useful in combination with filters that handle None (or any
79 false value) specially, such as the 'default' filter, when one
80 wants special treatment for the NaN value. It is also useful
81 before the 'format' filter to avoid the NaN value being formatted.
83 """
84 if is_nan(value):
85 return None
86 return value

Related snippets