【发布时间】:2020-11-07 10:16:30
【问题描述】:
给定一个如下所示的 DataFrame:
id days cluster
0 aaa 0 0
1 bbb 0 0
2 ccc 0 1
3 ddd 0 1
4 eee 0 0
5 fff 0 1
6 ggg 1 0
7 hhh 1 1
8 iii 1 0
9 lll 1 1
10 mmm 1 1
11 aaa 1 3
12 bbb 1 3
我的目标是创建一个字典,其中包含 id 列的元素的键元组和作为值的 cluster 列的元素列表,如果两个 id 具有相同的 cluster 值,全部过滤通过days 列。即,如果 days 更改但 id 元素的元组具有相同的 cluster 值,我想将此值添加到我已经存在的列表中。所需的输出报告如下:
{('aaa', 'bbb'): [0, 3],('aaa', 'eee'): [0], ('bbb', 'eee'): [0], ('ccc', 'ddd'): [1],
('ccc', 'fff'): [1], ('ddd', 'fff'): [1], ('ggg', 'iii'): [0],
('hhh', 'lll'): [1], ('hhh', 'mmm'): [1], ('lll', 'mmm'): [1]}
我用下面的 sn-p 代码得到了这个结果,但是有百万行它变得太慢了。如何优化代码?
y={}
for i in range(0, max(df.iloc[:,1]) + 1):
x = df.loc[df['days'] == i]
for j in range(0,l en(x)):
for z in range(1, len(x)):
if (x.iloc[z,0], x.iloc[j,0]) in y:
pass
else:
if (x.iloc[j,0], x.iloc[z,0]) not in y:
if x.iloc[j,0] != x.iloc[z,0] and x.iloc[j,2] == x.iloc[z,2]:
y[(x.iloc[j,0], x.iloc[z,0])] = [x.iloc[j,2]]
else:
if x.iloc[j,0] != x.iloc[z,0] and x.iloc[j,2] == x.iloc[z,2]:
y[(x.iloc[j,0], x.iloc[z,0])].append(x.iloc[j,2])
【问题讨论】:
-
在您的示例中,ID 'aaa' 可能的集群值是 0 和 3(分别代表第 0 天和第 1 天)。但在您想要的输出中,ID 'aaa' 与 'ccc'、'ddd'、'fff'、'hhh'、'llll' 和 'mmm' 分组,它们的聚类值为 1 或 2。所以我不明白你的说法
if the two 'id' have the same 'cluster' value。 -
@mtrw 你是对的!修复它,我发布的所需输出是错误的!谢谢
标签: python loops dataframe dictionary optimization