假设我有一个2dnumpy数组,其中每一行表示一个唯一的项,而行中的每一列表示分配给该项的标签。例如,在这个实例中,一个10x25数组将表示10个项目,每个项目最多有25个标签。你知道吗
将其转换为dict(或者另一个适当的数据类型,如果可以按长度排序的话,还可以加分)的最有效方法是什么?dict将标签映射到标签所在的行索引中?例如,dict[1]
将返回包含1
作为标签的行索引列表。你知道吗
例如
Given:
[1, 2, 3]
[1, 0, 0]
[1, 3, 0]
Result:
1: 0, 1, 2 # 1 occurs in rows 0, 1, 2
3: 0, 2 # 3 occurs in rows 0, 2
0: 1, 2 # 0 occurs in rows 1, 2 (0 is padding for lack of labels)
2: 0 # 2 occurs in row 0 only
更新:添加按长度排序。你知道吗
我们可以使用高级索引来创建按项目和标签索引的网格。 然后我们可以在列上迭代并使用
flatnonzero
来获得项目id:请注意,字典记住键的插入顺序。这是3.6中的一个实现细节,但将是3.7中的一个保证特性。你知道吗
在使用
OrderedDict
按观察数排序之前,可以使用collections.defaultdict
:您只需定义一个
{}
并遍历数组,边添加值,如下所示:这种方法是O(N2)。这是因为set()是线性的,被称为N次。而且,集合成员是常数时间。你知道吗
相关问题 更多 >
编程相关推荐