Skip to content Skip to sidebar Skip to footer

How To Replace Elements Of A Numpy Array From Two Different Arrays

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 e

Solution 1:

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]

Post a Comment for "How To Replace Elements Of A Numpy Array From Two Different Arrays"