将2个单维数组排序为1维数组



我正试图编写一个代码,从ab逐个选择。我想做一个二维数组第一个下标是0 or 10代表a,1代表b,第二个索引将只是数组ab中的值,因此它将类似于[[0 7][1 13]]。我想要这个函数也有它的顺序,所以它将是,函数从a开始,然后它将像a,b,a,b,a...,如果它是b,a,b,a,b...的另一种方式。由于b的第一个索引是0,a的第一个索引是7,所以比较哪个索引函数在另一个索引函数之前,因为0 <7代码将从b[[1 0]]开始,然后它将转到'a'的下一个索引,即7,即[[1 0],[0, 7]]。它将继续这样做,直到到达数组ab的末尾。我怎样才能得到下面的预期输出呢?

import numpy as np
a = np.array([ 7,  9, 12, 15, 17, 22])
b = np.array([ 0, 13, 17, 18])

预期输出:

[[ 1  0]
[ 0  7]
[ 1  13]
[ 0  15]
[ 1  17]
[ 0  17]
[ 1  18]
[ 0  22]]

您可以组合两个数组并在保留每个值的原点(使用2N和2N+1偏移)的情况下对值进行排序。

然后过滤掉连续的奇/偶值,只保留具有交替原点指示符(1或0)的值

最后,通过反转2N和2N+1标记来构建[origin,value]对的结果数组。

import numpy as np
a = np.array([ 7,  9, 12, 15, 17, 22])
b = np.array([ 0, 13, 17, 18])
p = 1 if a[0] > b[0] else 0 # determine first entry
c = np.sort(np.concatenate((a*2+p,b*2+1-p)))  # combine/sort tagged values
c = np.concatenate((c[:1],c[1:][c[:-1]%2 != c[1:]%2])) # filter out same-array repeats
c = np.concatenate(((c[:,None]+p)%2,c[:,None]//2),axis=1) # build result
print(c)

[[ 1  0]
[ 0  7]
[ 1 13]
[ 0 15]
[ 1 17]
[ 0 17]
[ 1 18]
[ 0 22]]

这不是Numpy解决方案,但如果您可以将这些作为列表处理,则可能有效。您可以从列表中创建迭代器,然后使用itertools.dropwhile在它们之间交替进行遍历元素,直到获得下一个元素。它可能看起来像:

from itertools import dropwhile
def pairs(a, b):
index = 0 if a[0] <= b[0] else 1
iters = [iter(a), iter(b)]   
while True:
try:
current = next(iters[index])
yield [index,current]
index = int(not index)
except StopIteration:
break
iters[index] = dropwhile(lambda n: n < current, iters[index])

list(pairs(a, b))

结果是:

[[1, 0], [0, 7], [1, 13], [0, 15], [1, 17], [0, 17], [1, 18], [0, 22]]

可以使用数组元素来自的条件->使用排序值->包括->group wise split和->flip条件

c = np.hstack([np.vstack([a, np.zeros(len(a))]), np.vstack([b, np.ones(len(b))])]).T
c = c[c[:, 0].argsort()]
# Group wise split and flip array - 2nd possiblity
d = np.vstack(np.apply_along_axis(np.flip, 0, np.split(c, np.unique(c[:,0], return_index = True)[1])))[::-1]
res1 = np.vstack([d[0], d[1:][d[:,1][:-1]!=d[:,1][1:]]])
res2 = np.vstack([c[0], c[1:][c[:,1][:-1]!=c[:,1][1:]]])
if res1.shape[0]>res2.shape[0]:
print(res1)
else:
print(res2)

:

[[ 0.  1.]
[ 7.  0.]
[13.  1.]
[15.  0.]
[17.  1.]
[17.  0.]
[18.  1.]
[22.  0.]]

最新更新