首页 > 解决方案 > 比较数据框列中字典的键

问题描述

我有一个像 -

Challenge       Points
challenge1      {'k01-001': 0.5, 'k03-015':0.3, 'k01-005': 0.2}
challenge2      {'k02-001': 0.5, 'k06-003':0.4, 'k04-001': 0.1}
challenge3      {'k04-001': 0.1, 'k06-003':0.9}
challenge4      {'k01-005': 0.2, 'k01-001':0.4, 'k03-002': 0.2, 'k01-007': 0.2}
challenge5      {'k06-003': 0.6, 'k04-001':0.4}

从这里我想制作一个字典,其中的键应该是两个点的元组,它们已经一起评估了一个挑战(例如('k01-001', 'k01-005')),值应该是他们一起评估了多少个挑战。所以,像 -

{('k01-001', 'k01-005'): 2, ('k01-001', 'k03-015'): 1, ('k01-005', 'k03-015'): 1, ('k04-001', 'k06-003'): 3, ... }

到目前为止,我已经设法Points使用此代码阅读列中的各个字典 -

for index, row in df.iterrows():
    dict_temp = json.loads(row['Points'].replace("'", '"'))    
    for key, value in dict_temp.items():
        # SOME CODE HERE

但是,我不确定如何从这里开始。

标签: python-3.xpandasdataframedictionary

解决方案


我会使用mapandreduce和 defaultdict 来计算:

from collections import defaultdict
from functools import reduce
from itertools import combinations

combs = reduce(lambda x, y: x + y, 
               map(lambda x: tuple(map(sorted, combinations(list(x), 2))) ,
                   df['Points']))

d = defaultdict(int)
for comb in combs:
    d[tuple(comb)] += 1
d = dict(d)
print(d)

{('k01-001', 'k03-015'): 1, ('k01-001', 'k01-005'): 2, ('k01-005', 'k03-015'): 1,
 ('k02-001', 'k06-003'): 1, ('k02-001', 'k04-001'): 1, ('k04-001', 'k06-003'): 3,
 ('k01-005', 'k03-002'): 1, ('k01-005', 'k01-007'): 1, ('k01-001', 'k03-002'): 1, 
 ('k01-001', 'k01-007'): 1,('k01-007', 'k03-002'): 1}

时间比较:

%%timeit
combs = reduce(lambda x,y: x + y, 
               map(lambda x: tuple(map(sorted, combinations(list(x), 2))) ,
                   df['Points']))

d = defaultdict(int)
for comb in combs:
    d[tuple(comb)]+=1
d = dict(d)
26.2 µs ± 439 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%%timeit
s=(df.Points.apply(lambda x: tuple(itertools.combinations(x.keys(), 2))).explode()
    .apply(lambda x : tuple(sorted(x))).value_counts()).to_dict()
1.69 ms ± 62.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

推荐阅读