问题
I have one simple program below:
import numpy as np
arr = np.random.randn(8)
new = arr.sort()
new1 = np.sort(arr)
print new
print new1
I expected the two new arrays to be the same a sorted array, but instead, new
is None
, new1
is what I expected, what is the difference between two methods to sort?
回答1:
From the documentation for numpy.ndarray.sort
:
Sort an array, in-place.
If you want a sorted copy of the original array, rather than sorting in place, you should use numpy.sort
, which returns a copy, as you saw.
回答2:
np.random.randn(8)
will return an array and arr.sort()
will return None
i.e new
is None
because .sort()
is made to work with only lists not with arrays so you have to use sorted(arr)
for sorting an array in python. If you do so there are no much difference between sorted(arr)
and np.sort(arr)
来源:https://stackoverflow.com/questions/45023833/numpy-sort-function-returns-none