python-3.x - 比较数据框列中字典的键
问题描述
我有一个像 -
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
但是,我不确定如何从这里开始。
解决方案
我会使用map
andreduce
和 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)
推荐阅读
- ssis - SSIS 表达式任务功能但不能在标题中工作
- android - How do I find the search query text in a debugger?
- python - Python object of type long has no Len() error?
- java - 如果不起作用,为什么这么短?message.startsWith("www.")? JOptionPane.showMessageDialog(win, "Url is") :
- php - 为什么安装时缺少 mysqli 类?
- wordpress - 从浏览器访问 wordpress 主页的问题
- oracle-apex - 在 oracle apex 中应用电话号码格式掩码
- java - java.io.IOException:使用 JVM v1.8.0_162 启动 Tomcat v9.0.2.0 时无法建立环回连接
- python - 计算许多分布的 KL 散度
- javascript - 同一台机器上的两个节点脚本可以互相阻塞吗?