【发布时间】:2016-06-23 09:28:37
【问题描述】:
我正在寻找加快(或替换)我的数据分组算法的方法。
我有一个 numpy 数组列表。我想生成一个新的 numpy 数组,这样该数组的每个元素对于原始数组也相同的每个索引都是相同的。 (在不是这种情况的情况下有所不同。)
这听起来有点尴尬,所以举个例子:
# Test values:
values = [
np.array([10, 11, 10, 11, 10, 11, 10]),
np.array([21, 21, 22, 22, 21, 22, 23]),
]
# Expected outcome: np.array([0, 1, 2, 3, 0, 3, 4])
# * *
请注意,我标记的预期结果的元素(索引 0 和 4)具有相同的值(0),因为原始的两个数组也相同(即10 和21)。索引为 3 和 5 的元素类似 (3)。
该算法必须处理任意数量(大小相等)的输入数组,并且还为每个结果数返回它们对应的原始数组的值。 (所以对于这个例子,“3”指的是(11, 22)。)
这是我目前的算法:
import numpy as np
def groupify(values):
group = np.zeros((len(values[0]),), dtype=np.int64) - 1 # Magic number: -1 means ungrouped.
group_meanings = {}
next_hash = 0
matching = np.ones((len(values[0]),), dtype=bool)
while any(group == -1):
this_combo = {}
matching[:] = (group == -1)
first_ungrouped_idx = np.where(matching)[0][0]
for curr_id, value_array in enumerate(values):
needed_value = value_array[first_ungrouped_idx]
matching[matching] = value_array[matching] == needed_value
this_combo[curr_id] = needed_value
# Assign all of the found elements to a new group
group[matching] = next_hash
group_meanings[next_hash] = this_combo
next_hash += 1
return group, group_meanings
请注意,表达式 value_array[matching] == needed_value 会针对每个单独的索引进行多次评估,这就是缓慢的原因。
我不确定我的算法是否可以进一步加快速度,但我也不确定它是否是开始时的最佳算法。有更好的方法吗?
【问题讨论】:
标签: python performance numpy