1

I have a numpy array -

['L', 'London', 'M', 'Moscow', 'NYC', 'Paris', 'nan']

I want 'nan' to be first, like so:

['nan', 'L', 'London', 'M', 'Moscow', 'NYC', 'Paris']

How can I do that?

Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • Does this answer your question? [Python Array Rotation](https://stackoverflow.com/questions/17350330/python-array-rotation) – Arkistarvh Kltzuonstev Jul 23 '20 at 18:32
  • Is `nan` always last, or can it be anywhere? In general this isn't an efficient operation in numpy. – hpaulj Jul 23 '20 at 20:31
  • It can be anyway. I modified Andrej's answer to find the location of the 'nan' then subtract it from the size of the array then shift it by that amount so the value 'nan'(or any I choose in the future) will always be first. – Lostsoul Jul 23 '20 at 21:05

1 Answers1

3

If you want to use numpy, you can use numpy.roll:

a = np.array(['L', 'London', 'M', 'Moscow', 'NYC', 'Paris', 'nan'])

a = np.roll(a, 1)

print(a)

Prints:

['nan' 'L' 'London' 'M' 'Moscow' 'NYC' 'Paris']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Thank you Andrej! It worked. I made a slight modification to find the location then shift by that amount regardless of the position of the value I want to roll - locationOfNaN = np.where(a == 'nan')[0][0] #find location of value DistanceToRoll = (len(a)) - (locationOfNaN) then roll by DistanceToRoll to make it dynamic. Thank you. – Lostsoul Jul 23 '20 at 21:07