For an array
array2 = np.array([np.nan, np.nan, np.nan, np.nan, 45, np.nan, 33, np.nan,
np.nan, 32, np.nan, np.nan, 44, np.nan, 10, 53, np.nan])
I need to replace elements consequently by condition: if an element is less than np.mean(array2), it should be taken from ordered_array_1 = [32, 10, 33]
, otherwise - from ordered_array_2 = [44, 53, 45]
.
I haven't managed to use np.putmask, or numpy.where for that purpose, as for example np.putmask(array2[~np.isnan(array2)],mask,ordered1)
doesn't replace elements at all. The array2 doesn't change.
I expect this result after replacement from both arrays:
array2 = np.array([np.nan, np.nan, np.nan, np.nan, 44, np.nan, 32, np.nan,
np.nan, 10, np.nan, np.nan, 53, np.nan, 33, 45, np.nan])
CodePudding user response:
Use np.where
np.nanmean
as follows:
import numpy as np
array2 = np.array([np.nan, np.nan, np.nan, np.nan, 45, np.nan, 33, np.nan,
np.nan, 32, np.nan, np.nan, 44, np.nan, 10, 53, np.nan])
ordered_array_1 = [32, 10, 33]
ordered_array_2 = [44, 53, 45]
array2[np.where(array2 < np.nanmean(array2))] = ordered_array_1
array2[np.where(array2 >= np.nanmean(array2))] = ordered_array_2
print(array2)
Output
[nan nan nan nan 44. nan 32. nan nan 10. nan nan 53. nan 33. 45. nan]