我有一个numpy数组T,其行具有以下列结构:[x, y, value],其中x,y,value是整数。示例T数组如下所示:
[[1, 0, 4],
[0, 2, 3],
[1, 2, 7]]该数据来自第三列指定元组(x, y)的变量值的模型。在模型中,这个元组对应于值的标签。例如,我的标签T_10 (下标10)有值4,T_02有值3,T_12有值7。
现在,我想换一双标签。例如,我希望将所有标签2替换为1 (反之亦然),以便分别获得前面示例的T_20、T_01和T_21。所以,这个新的数据是
U = [[2, 0, ?],
[0, 1, ?],
[2, 1, ?]]我的问题是,我不知道如何使我的新数据看起来像这样:
U = [[2, 0, -3]
[0, 1, -4],
[2, 1, -7]]这个新数据应该遵循的两条规则
first ,它应该正确识别T的行,其第一列和第二列(x, y)与U中的新(x, y)相同。对于每一行U,如果排序对(x, y) = (x, y) of T,那么适当的'?‘U第三列中的值应该是T中的相应值。
第二:另一方面,如果(x, y) of U = (y, x) of T,那么它应该是对应value的负值。
我的尝试包括首先提取T的列,然后使用以下函数交换这对标签:
def swap_indices(a, pair):
for n, i in enumerate(a):
if i == pair[0]: # check whether a0's element is = swap element 1
a[n] = pair[1]
elif i == pair[1]:
a[n] = pair[0]
return a 例如,我将使用以下方法将标签0与1交换,反之亦然,将标签转换为列x和列y:
pair = (0, 1)
a0 = swap_indices(T[:,0], pair) # column x
a1 = swap_indices(T[:,1], pair) # column y 然后迭代T;num_rows_of_T的行数。
for k in range(num_rows_of_T):
temp = np.where((T[k, 0] == a0[k]) & (T[k, 1] == a1[k]) | ((T[k, 0] == a1[k]) & (T[k, 1] == a0[k])))上面,我试图获取行的索引,其中(x, y) of U = (x, y) of T,或(x, y) of U = (y, x) of T。然而,这正是我被困的地方。我觉得上面的话不对。此外,这种方法不允许我应用第二规则,其中取T if (x, y) = (y, x)值的负值。我还尝试对starters使用set() (以获得无序对),但即使这样,我也无法正确地找到T的对应值。
基本上,我希望找到与value中的新标签匹配的T的U s。我的数据很好,因为可能只有一个可能的坐标集,而且在(x,y) of T和U之间总是有一个双射映射(考虑到我的两个规则)。
有什么建议吗?如有必要,请帮助编辑问题。我很难问。
下面是一个最低限度的工作示例:
import numpy as np
# swap index labels if match swap pair
def swap_indices(a, pair):
for n, i in enumerate(a):
if i == pair[0]: # check whether a0's element is = swap element 1
a[n] = pair[1]
elif i == pair[1]:
a[n] = pair[0]
return a
def find_valid_swaps(The1 = np.array([1, 0, -1, 1, 0, 1]), headers = np.array(['10', '20', '21', '30', '31', '32'])):
num_indices = len(The1)
T = np.zeros((num_indices,3)); U = T;
# match format given for T in question
for i in range(num_indices):
T[i,:] = [int(list(headers[i])[0]), int(list(headers[i])[1]), The1[i]]
pair = (0, 1) # label pair to swap
a0 = swap_indices(T[:, 0], pair) # column 0 of U
a1 = swap_indices(T[:, 1], pair) # column 1 of U
# try to extract correct 'value' from T based on new labels in U
for k in range(num_indices):
temp = np.where((T[k, 0] == a0[k]) & (T[k, 1] == a1[k]) | ((T[k, 0] == a1[k]) & (T[k, 1] == a0[k])))
print("temp",temp[0][0])
U[k, :] = [a0[k], a1[k], T[temp[0][0], 2]] # here, I would finally create the new U matrix, applying both rules
print(U)
find_valid_swaps()更多的例子使用@MadPhysicist的答案:
# swap index labels if match swap pair
def swap_indices(a, pair):
for n, i in enumerate(a):
if i == pair[0]: # check whether a0's element is = swap element 1
a[n] = pair[1]
elif i == pair[1]:
a[n] = pair[0]
return a
def key(arr, m):
return arr[:, 0] * m + arr[:, 1]
def find_valid_swaps(Thetas1 = np.array([1, 1, 0, 0, -1, -1]), Thetas2 = np.array([1, 0, -1, 1, 0, 1]), num_bands = 4, headers = np.array(['10', '20', '21', '30', '31', '32'])):
import itertools # for permutations: https://stackoverflow.com/questions/40092474/get-all-pairwise-combinations-from-a-list
if (Thetas1==Thetas2).all():
print("Warning: Input sets of indices are equal to each other. Will check other possible permutations regardless.")
else:
print("Input sets of indices are unique. Will proceed checking other viable permutations.")
num_indices = len(Thetas1)
T = np.zeros((num_indices,3))
U = np.zeros((num_indices,3))
for i in range(num_indices):
T[i,:] = [int(list(headers[i])[0]), int(list(headers[i])[1]), Thetas2[i]]
print("input T")
print(T)
pair = (2,3)
a0 = swap_indices(T[:,0], pair) # column 1
a1 = swap_indices(T[:,1], pair) # column 2
for k in range(num_indices):
U[k, :] = [a0[k], a1[k], 0]
# below code due to @MadPhysicist from https://stackoverflow.com/questions/67223782/mapping-zs-in-numpy-array-a-x0-y0-z0-x1-y1-z1-for-3rd-column-of-ar/67235030?noredirect=1#67235030
y_max = T[:, 1].max() + 1
Tkey = key(T, y_max)
s = np.argsort(Tkey)
Ukey = key(U, y_max)
i = np.searchsorted(Tkey, Ukey, sorter=s)
i[i == len(i)] -= 1 # cleanup indices that won't match anyway
mask = (Ukey == Tkey[s[i]])
U2key = key(U[~mask, 1::-1], y_max)
j = np.searchsorted(Tkey, U2key, sorter=s)
U[mask, -1] = T[s[i[mask]], -1]
U[~mask, -1] = -T[s[j], -1]
print("reordered U")
print(U)以上提供了输出:
input T
[[ 1., 0., 1.]
[ 2., 0., 0.]
[ 2., 1., -1.]
[ 3., 0., 1.]
[ 3., 1., 0.]
[ 3., 2., 1.]]
reordered U
[[ 1., 0., 1.]
[ 3., 0., 0.]
[ 3., 1., -1.]
[ 2., 0., 1.]
[ 2., 1., 0.]
[ 2., 3., 1.]]发布于 2021-04-23 18:16:43
您可以将算法归纳为三大步骤:
中的剩余Uyx
组合结果显然是非常琐碎的。整个操作应该可以在O(N log N)时间内完成,因为这是每个步骤所需的时间。
由于np.searchsorted是步骤2和步骤3的主要候选项,所以假设您可以将前两列转换为唯一的键。例如,假设在所有情况下都是y <= y_max,而y_max有一个正常的界限,因此x * y_max + y <= 2**32-1适用于所有x。您可以在闲暇时使用np.int64或使用x_max代替y_max。
所以现在你做了:
def key(arr, m):
return arr[:, 0] * m + arr[:, 1]
y_max = T[:, :1].max(None) + 1
Tkey = key(T, y_max)
s = np.argsort(Tkey)要查找U的哪些元素匹配:
Ukey = key(U, y_max)
i = np.searchsorted(Tkey, Ukey, sorter=s)
i[i == len(i)] -= 1 # cleanup indices that won't match anyway
mask = (Ukey == Tkey[s[i]])现在找到反向索引。
U2key = key(U[~mask, 1::-1], y_max)
j = np.searchsorted(Tkey, U2key, sorter=s)由于映射是双射的,因此此步骤只搜索保证存在的元素,并且不需要验证索引。
现在你可以组合这些指数了。如果U还没有第三列,那么添加一列:
U = np.concatenate((U, np.empty_like(T[:, :1])), axis=1)使用我们计算的索引,提取您想要的Tsort元素:
U[mask, -1] = T[s[i[mask]], -1]
U[~mask, -1] = -T[s[j], -1]现在,如果您无法获得像key这样的映射,那么事情可能会更复杂一些。如果没有别的办法,先试一试
def key(arr):
return arr[:, 0] + 1j * arr[:, 1]复杂值将仅用作排序键,而不用作其他任何内容。如果失败,您可能必须定义一个结构化数据类型,并通过该类型查看数组,以使搜索工作正常。当然,您可以实现分层搜索,但我觉得这超出了这里的范围。
下面是一个基于您的T的完整的玩具示例,其中有一个稍微修改过的U,它在最后一栏中显示了正数和负数:
>>> T = np.array([[1, 0, 4],
[0, 2, 3],
[1, 2, 7]])
>>> U = np.array([[2, 1, 0],
[1, 0, 0],
[2, 0, 0]])
>>> def key(arr, m):
... return arr[:, 0] * m + arr[:, 1]
>>> y_max = T[:, :1].max(None) + 1
>>> Tkey = key(T, y_max)
>>> s = np.argsort(Tkey)
>>> Ukey = key(U, y_max)
>>> i = np.searchsorted(Tkey, Ukey, sorter=s)
>>> i[i == len(i)] -= 1 # cleanup indices that won't match anyway
>>> mask = (Ukey == Tkey[s[i]])
>>> U2key = key(U[~mask, 1::-1], y_max)
>>> j = np.searchsorted(Tkey, U2key, sorter=s)
>>> U[mask, -1] = T[s[i[mask]], -1]
>>> U[~mask, -1] = -T[s[j], -1]
>>> print(U)
[[ 2 1 -7]
[ 1 0 4]
[ 2 0 -3]]https://stackoverflow.com/questions/67223782
复制相似问题