1

I have a numpy array atoms.numbers which looks like:


array([27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57, 57, 57, 57, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57,
       57, 57, 57, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

I can replace all of the same instance such as every '57' in the array using:

atoms.numbers[atoms.numbers==57]=38

which gives:

array([27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38, 38, 38, 38, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38,
       38, 38, 38, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

I would like to be able to replace every nth instance in the array. I have tried:

n=5
atoms.numbers[atoms.numbers==57][::n]=38

Which does not work.

  • What is the purpose of `[atoms.numbers==57]` in the second example? Do you want to replace every 5th number that is equal 57? – DYZ May 30 '20 at 04:37
  • Yes the example was to show that I can replace every instance of '57' in the array. I want to be able to replace every 5th instance of '57' in the array with '38'. – Dallon Penney May 30 '20 at 04:44

1 Answers1

1

Use np.where to find the indexes of the items of interest. Find every n'th index. Update the items:

locations = np.where(numbers == 57)[0]
numbers[locations[::n]] = 38
DYZ
  • 55,249
  • 10
  • 64
  • 93