Ale*_*lex 1 python arrays algorithm numpy
我需要同时对两个数组进行排序,或者更确切地说,我需要对其中一个数组进行排序,并在排序时将其关联数组的相应元素与它一起使用.那就是如果数组是[(5,33),(4,44),(3,55)]并且我按第一轴排序(标记为dtype ='alpha')那么我想:[(3.0,55.0 )(4.0,44.0)(5.0,33.0)].这些都是非常大的数据集,我需要先排序(对于nlog(n)速度),然后再进行其他操作.我不知道如何以正确的方式合并我的两个单独的数组,以使排序算法工作.我认为我的问题很简单.我尝试了三种不同的方法:
import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])
dtype=[('alpha',float), ('beta',float)]
values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values
values=numpy.empty((len(x),2))
for n in range (len(x)):
values[n][0]=y[n]
values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')
print "Result:\n",q
Run Code Online (Sandbox Code Playgroud)
我评论了第一个和第二个版本,因为它们会产生错误,我知道第三个版本会起作用,因为这反映了我在RTFM时所看到的内容.给定数组x和y(非常大,只显示示例)如何构造可以被numpy.sort正确调用的数组(称为值)?
***Zip很棒,谢谢.奖金问题:我怎样才能将排序后的数据再次解压缩成两个数组?
我想你想要的是zip功能.如果你有
x = [1,2,3]
y = [4,5,6]
Run Code Online (Sandbox Code Playgroud)
然后 zip(x,y) == [(1,4),(2,5),(3,6)]
所以你的数组可以用
a = numpy.array(zip(x,y), dtype=dtype)
Run Code Online (Sandbox Code Playgroud)