gpt4 book ai didi

python - 根据一列中的公共(public)值从两个或多个 2d numpy 数组创建交集

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:28 31 4
gpt4 key购买 nike

我有 3 个具有以下结构的 numpy recarrays。第一列是某个位置(整数),第二列是分数( float )。

输入:

a = [[1, 5.41],
[2, 5.42],
[3, 12.32],
dtype=[('position', '<i4'), ('score', '<f4')])
]

b = [[3, 8.41],
[6, 7.42],
[4, 6.32],
dtype=[('position', '<i4'), ('score', '<f4')])
]

c = [[3, 7.41],
[7, 6.42],
[1, 5.32],
dtype=[('position', '<i4'), ('score', '<f4')])
]

所有 3 个数组包含相同数量的元素。
我正在寻找一种基于位置列将这三个二维数组组合成一个数组的有效方法。

上面例子的输出数组应该是这样的:

输出:

output = [[3, 12.32, 8.41, 7.41],
dtype=[('position', '<i4'), ('score1', '<f4'),('score2', '<f4'),('score3', '<f4')])]

输出数组中只有位置为 3 的行,因为该位置出现在所有 3 个输入数组中。

更新:我天真的方法是遵循以下步骤:

  1. 为我的 3 个输入数组的第一列创建向量。
  2. 使用 intersect1D 获取这 3 个向量的交集。
  3. 以某种方式检索所有 3 个输入数组的向量索引。
  4. 使用来自 3 个输入数组的过滤行创建新数组。

更新 2:每个位置值可以在一个、两个或所有三个输入数组中。在我的输出数组中,我只想包含所有 3 个输入数组中出现的位置值的行。

最佳答案

这是一种方法,我相信它应该相当快。我想你要做的第一件事就是计算每个位置的出现次数。此函数将处理:

def count_positions(positions):
positions = np.sort(positions)
diff = np.ones(len(positions), 'bool')
diff[:-1] = positions[1:] != positions[:-1]
count = diff.nonzero()[0]
count[1:] = count[1:] - count[:-1]
count[0] += 1
uniqPositions = positions[diff]
return uniqPositions, count

现在使用上面的函数形式,您只想取出现 3 次的位置:

positions = np.concatenate((a['position'], b['position'], c['position']))
uinqPos, count = count_positions(positions)
uinqPos = uinqPos[count == 3]

我们将使用搜索排序,所以我们对 b 和 c 进行排序:

a.sort(order='position')
b.sort(order='position')
c.sort(order='position')

现在我们可以通过用户搜索排序来查找每个数组中的位置来找到我们的每个 uniqPos:

new_array = np.empty((len(uinqPos), 4))
new_array[:, 0] = uinqPos
index = a['position'].searchsorted(uinqPos)
new_array[:, 1] = a['score'][index]
index = b['position'].searchsorted(uinqPos)
new_array[:, 2] = b['score'][index]
index = c['position'].searchsorted(uinqPos)
new_array[:, 3] = c['score'][index]

使用字典可能有更优雅的解决方案,但我首先想到了这个,所以我会把它留给其他人。

关于python - 根据一列中的公共(public)值从两个或多个 2d numpy 数组创建交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975054/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com