【发布时间】:2014-09-23 10:36:58
【问题描述】:
我有两个字典 A 和 B,它们都有相同的键 a、b 和值。这些键后面的所有 3 个值都是相同大小的 numpy 数组,但 A 和 B 的大小可能不同。 如果找到此链接here,但它仅适用于一维键: 可以将 a(0),b(0) 组合视为笛卡尔空间中的坐标,将 value(0) 视为它们的值。我有两个数据集 A 和 B。 举个例子:
A = {'a': numpy.array([1, 1, 9, 9]),
'b': numpy.array([0, 1, 0, 1]),
'value': numpy.array([1, 2, 3, 4])}
B = {'a': numpy.array([1, 1, 7, 7]),
'b': numpy.array([0, 1, 0, 1]),
'value': numpy.array([101, 102, 1003, 1004])}
如果两个键相同,我需要对这些字典的值求和,否则我想附加键和值。 在示例中: 两个字典共享组合键 a:1 和 b:0,以及 a:1 和 b:1。它们的值相加为 1+101=102 和 2+102=104。 组合键 a:9, b:0 和 a:9, b:1 仅在字典 A 中 组合键 a:7, b:0 和 a:7, b:1 仅在字典 B 中 所以我想要这个结果
C = {'a': numpy.array([1, 1, 9, 9, 7, 7]),
'b': numpy.array([0, 1, 0, 1, 0, 1]),
'value': numpy.array([102, 104, 3, 4, 1003, 1004 ])}
我想出了一个解决方案,它采用字典 A 并通过添加或附加字典 B 中的内容来修改它。 因此,它首先为 A 中的二维键组合生成一维哈希键,为 B 中的二维键组合生成一个。然后使用 numpy.intersect() 查找两个字典中的公共键,并将 B 的值添加到A 在那个指数。然后我取交集的反转并将不常见的键和值都附加到字典 A.
def example(A, B):
# generate hash keys (32 bit shift because values in a and b are larger than in example)
hash_A = map(lambda a, b: (int(a) << 32) + int(b), A['a'], A['b'])
hash_B = map(lambda a, b: (int(a) << 32) + int(b), B['a'], B['b'])
# intersection is now 1-dimensional and easy
intersect = numpy.intersect1d(hash_A, hash_B)
# common keys
A['value'][numpy.in1d(hash_A, intersect)] += B['value'][numpy.in1d(hash_B, intersect)]
# keys only in B and not in A
only_in_B = numpy.in1d(hash_B, intersect, invert=True)
if any(only_in_B):
A['a'] = numpy.append(A['a'], B['a'][only_in_B])
A['value'] = numpy.append(A['value'], B['value'][only_in_B])
A['b'] = numpy.append(A['b'], B['b'][only_in_B])
return A
但我的解决方案似乎太慢而无用,我想不出更快的方法。 使用的 numpy.arrays 有数百万个条目,这是针对几种字典组合完成的。速度是个问题。 任何帮助将不胜感激。
【问题讨论】:
标签: python numpy dictionary hash merge