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?

3
  • Does this answer your question? Python Array Rotation Commented Jul 23, 2020 at 18:32
  • Is nan always last, or can it be anywhere? In general this isn't an efficient operation in numpy. Commented Jul 23, 2020 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. Commented Jul 23, 2020 at 21:05

1 Answer 1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.