Tro*_*H.H 6 python sorting numpy
你如何排序,操作,然后取消结果?
假设我有一个浮点数组p1 = 0.15,0.3, 0.25, 0.12, ....它分类为:p2 = sort(p1).函数(p2作为输入的操作)导致p3:p3 = f(p2, x, y, ...)对于某些函数f.
我怎样才能p3以最聪明的方式解开?(反过来如何p1排序)
ie: p4 = unsort(p3)< - p4未分类到相同的顺序p1,用于比较(x-plot)p1?
您需要在此处使用双 argsort 来保持顺序:
In [6]: a
Out[6]: array([5, 4, 8, 3, 6, 1, 2, 4, 9, 6])
In [7]: b=sort(a)
In [8]: b
Out[8]: array([1, 2, 3, 4, 4, 5, 6, 6, 8, 9])
In [9]: ii=a.argsort().argsort()
In [10]: c=b*b
In [11]: c
Out[11]: array([ 1, 4, 9, 16, 16, 25, 36, 36, 64, 81])
In [12]: c[ii]
Out[12]: array([25, 16, 64, 9, 36, 1, 4, 16, 81, 36])
Run Code Online (Sandbox Code Playgroud)
一种方法是使用numpy.argsort查找对初始数组进行排序的索引。相同的索引可用于将数组取消排序到其结果中,如下所示:
a = np.array([5, 2, 4, 3, 1])
i = np.argsort(a) # i = array([4, 1, 3, 2, 0])
# b will be the sorted version of a
b = a[i] # b = array([1, 2, 3, 4, 5])
# c is the function on b
c = b**2 # c = array([ 1, 4, 9, 16, 25])
# d will hold the un-sorted result
d = np.empty(a.shape)
d[i] = c # d = array([ 25., 4., 16., 9., 1.])
Run Code Online (Sandbox Code Playgroud)
但这需要您d在索引之前预先声明。