2

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])
4
  • What happens if there are more elements to replace that the ones on the list? If you have 4 elements to replace and only 3 in the list of replacements Commented Oct 13, 2021 at 14:02
  • Nothing happens )) And it is also strange (I mean np.putmask). Commented Oct 13, 2021 at 14:05
  • Sorry what should be the expected output the example I mentioned 4 elements to replace and only 3 replacements? Commented Oct 13, 2021 at 14:06
  • There can't be more elements, as ordered arrays are made from the array2 by exclusion and sorting Commented Oct 13, 2021 at 14:08

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

6 Comments

Works. There's only a warning: [32. 10. 33.] [45. 44. 53.] [False True True False True False] /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:13: RuntimeWarning: invalid value encountered in less del sys.path[0] /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:14: RuntimeWarning: invalid value encountered in greater array([nan, nan, nan, nan, 45., nan, 32., nan, nan, 10., nan, nan, 44., nan, 33., 53., nan])
@NikolayYasinskiy May I know which numpy version are you using? I don't get any warnings
I got numpy 1.17.2
I have 1.21.2 perhaps if you update the warning disappears
I would with pleasure, but when conda update numpy it says something about channel inconsistency and offers the ver. 1.17.2 from another channel. How would you update?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.