我正在尝试创建一个数组,用于保存其中一个(非常大的数组)与一组唯一值匹配的所有行。问题是这个大型数组将有多个匹配的行,我需要所有这些行都存储在新数组的同一行中。
使用for循环遍历每个唯一值是可行的,但速度太慢,无法使用。我一直在寻找一个矢量化的解决方案,但没有成功。任何帮助都将不胜感激!
arrStart = []
startRavel = startInforce['pol_id'].ravel()
for policy in unique_policies:
arrStart.append(np.argwhere(startRavel == policy))
新数组将具有与唯一值数组相同的长度,但每个元素将是大型数组中与该唯一值匹配的所有行的列表。
示例输入应该是这样的: startRavel = 1,2,2,2,3,3 unique_policies = 1,2,3
输出: arrStart = [,1,2,3,4,5]
发布于 2019-02-07 19:57:06
NumPy的一个可能选项,类似于您的,但在列表理解中是扁平化的:
startRavel = np.array([1,2,2,2,3,3])
unique_policies = np.array([1,2,3])
[np.argwhere(startRavel == policy).flatten() for policy in unique_policies]
#=> [array([0]), array([1, 2, 3]), array([4, 5])]
另一种方法,使用flatnonzero()
[np.flatnonzero(startRavel == policy) for policy in unique_policies]
生成器版本:
def matches_indexes(startRavel, unique_policies):
for policy in unique_policies:
yield np.flatnonzero(startRavel == policy)
https://stackoverflow.com/questions/54579972
复制