简体   繁体   中英

PyCharm numpy - sorting an array doesn't work?

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)

The reason is when you call sort() on the array itself, it sorts the array in-place:

arr.sort()

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

arr = np.sort(arr)

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 cas it returns a sorted copy of the array, and the original reamins the same. So it is not a malfunction of numpy in Pycharm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM