考虑下面所示的numpy数组p。每行都使用唯一值0至9。区别的特点是,每一行都由5个值(在本例中)与5个其他值配对而成。pk = p[pk] (k=0到9 )时形成对。
p = np.array([[1, 0, 3, 2, 5, 4, 7, 6, 9, 8],
...
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4],
...
[9, 8, 5, 7, 6, 2, 4, 3, 1, 0]])例如,检查行:
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4]该行对值为6和0,因为p[6] = 0和p[0] = 6。其他对是值(5,1),(3,2),(9,4),(8,7)。不同的行可能有不同的配对排列。
现在,我们感兴趣的是每对的 1值(即: 6、5、3、9、8)和每对的第2值(即: 0、1、2、4、7)--我不确定这是最好的方法,但我已经用这种方法将第一对值与第二对值分开了:
import numpy as np
p = np.array([6, 5, 3, 2, 9, 1, 0, 8, 7, 4])
p1 = np.where(p[p] < p) # indices of 1st member of pairs
p2 = (p[p1]) # indices of 2nd member of pairs
qi = np.hstack((p1, p2.reshape(1,5)))
qv = p[qi]
#output: qi = [0, 1, 2, 4, 7, 6, 5, 3, 9, 8] #indices of 1st of pair values, followed by 2nd of pair values
# qv = [6, 5, 3, 9, 8, 0, 1, 2, 4, 7] #corresponding values最后,考虑另一个一维数组:c = [1, 1, 1, 1, 1, -1, -1, -1, -1, -1]。
我发现c*qv,给:
out1 = [6, 5, 3, 9, 8, 0, -1, -2, -4, -7]问题: out1持有正确的值,但我需要它们保持原来的顺序(如p中所示)。如何才能做到这一点?我要得到:
out2 = [6, 5, 3, -2, 9, -1, 0, 8, -7, -4]发布于 2022-11-30 17:58:33
您可以重用p1和p2,它们保存了原始的位置信息。
out2 = np.zeros_like(out1)
out2[p1] = out1[:5]
out2[p2] = out1[5:]
print(out2)
# [ 6 5 3 -2 9 -1 0 8 -7 -4]也可以用qi达到类似的效果,但更整洁。
out2 = np.zeros_like(out1)
out2[qi] = out1或者使用np.put来防止您不想创建out2
np.put(out1, qi, out1)
print(out1)
# [ 6 5 3 -2 9 -1 0 8 -7 -4]2D案例
对于2D版本的问题,我们将使用类似的想法,但一些技巧时,索引。
p = np.array([[1, 0, 3, 2, 5, 4, 7, 6, 9, 8],
[6, 5, 3, 2, 9, 1, 0, 8, 7, 4],
[9, 8, 5, 7, 6, 2, 4, 3, 1, 0]])
c = np.array([1, 1, 1, 1, 1, -1, -1, -1, -1, -1])
p0 = np.arange(10) # this is equivalent to p[p] in 1D
p1_r, p1_c = np.where(p0 < p) # save both row and column indices
p2 = p[p1_r, p1_c]
# We will maintain row and column indices, not just qi
qi_r = np.hstack([p1_r.reshape(-1, 5), p1_r.reshape(-1, 5)]).ravel()
qi_c = np.hstack([p1_c.reshape(-1, 5), p2.reshape(-1, 5)]).ravel()
qv = p[qi_r, qi_c].reshape(-1, 10)
out1 = qv * c
# Use qi_r and qi_c to restore the position
out2 = np.zeros_like(out1)
out2[qi_r, qi_c] = out1.ravel()
print(out2)
# [[ 1 0 3 -2 5 -4 7 -6 9 -8]
# [ 6 5 3 -2 9 -1 0 8 -7 -4]
# [ 9 8 5 7 6 -2 -4 -3 -1 0]]请随意打印出每一个中间变量,这将帮助您了解正在发生的事情。
https://stackoverflow.com/questions/74631559
复制相似问题