Home > Back-end >  PyCharm numpy - sorting an array doesn't work?
PyCharm numpy - sorting an array doesn't work?

Time:11-18

I was trying to run some code and sort an array, below is the code. Online it says that an array can be sorted using this way but when I run this code, the output is None instead of the sorted code, can someone explain why? In Jupyter Notebook it works fine when I tested it. Both ways don't work - why is that ?

import numpy as np
arr = np.array([3, 7, 6, 8, 9, 1, 2, 3])
arr_sorted = arr.sort()
print(arr_sorted)

# alternative way 
arr_sorted2 = np.ndarray.sort(arr)
    print(arr_sorted2)

Additionally I found that this works instead - but I still don't know the why.

print(np.sort(arr))
ab = np.sort(arr)
print(ab)

enter image description here

CodePudding user response:

The reason is when you call sort() on the array itself, it sorts the array in-place and returns None, so arr_sorted is None too in the first part of your code. Better call the method ins this way:

arr.sort()

This is also the case for np.ndarray.sort(arr), therefore arr_sorted2 is also None.

But, calling np.sort(arr) returns the sorted array as another object, and it should be called in this way:

arr = np.sort(arr)

The behavior is the same for Jupyter, you may need to restart your notebook and try again to get valid outputs from your code, because the notebook might held the last state of your variables.

CodePudding user response:

If you take 'sort' as the method of class ndarray, it sort the array in place and returns None, but if you use 'sort' like a funcion of numpy by calling 'np.sort', then in this case it returns a sorted copy of the array, and the original reamins the same. So it is not a malfunction of numpy in Pycharm

  • Related