gpt4 book ai didi

python - Pandas 数据框每两行的组合

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:24 25 4
gpt4 key购买 nike

我正在实现一种聚类算法,该算法需要计算每对数据点之间的距离,其中每个数据点作为行存储在 pd.Dataframe 中。总计算量按 O(n^2) 的顺序增长,我必须谨慎才能有效地完成此操作。

做我想做的事情的有效方法是什么?

假设我的数据框中有 4 个数据点:

#<inputtable tin>
Id Label
0 Michael
1 Jim
2 Pam
3 Dwight

我需要运行一个自定义函数similar(x,y)来计算每两点 Combination(2,4) ~ 6 之间的折扣,我的输出应该是这样的:

#<outputtable tout>
Source_Id Source_Label To_Id To_Label distance
0 Michael 1 Jim f('Michael', 'Jim')
0 Michael 2 Pam f('Michael', 'Pam')
0 Michael 3 Dwight f('Michael', 'Dwight')
1 Jim 2 Pam f('Jim', 'Pam')
1 Jim 3 Dwight f('Jim', 'Dwight')
2 Pam 3 Dwight f('Pam', 'Dwight')

我做了什么:

我尝试使用 pd.merge 为表生成笛卡尔积

data = pd.DataFrame([[0, 'Michael'], [1, 'Jim'], [2, 'Pam'], [3, 'Dwight']], columns=['Id', 'Label'])
data['tmp'] = 1
result = pd.merge(data, data, left_on='tmp', right_on='tmp')
result = result[result['Id_x'] != result['Id_y']]
print result

然而,这看起来真的像是围绕合并的黑客攻击,我还尝试了 itertools 与组合,但它与 Pandas 的效果不太好。

有人知道使用自定义的相似距离函数进行此类“聚类工作”的更有效方法吗?我还计划在 Gephi 中进行分析,我不知道是否有更好的解决方案。

最佳答案

首先
我无法解决 O(n^2) 问题。

itertools.combination

from itertools import combinations

labels = df.Label.values.tolist()

f = lambda x, y: x + y

pd.Series({k: f(*k) for k in combinations(labels, 2)})

np.triu_indices

labels = df.Label.values

f = lambda x, y: x + y

i, j = np.triu_indices(labels.size, 1)

combs = list(zip(labels[i], labels[j]))

pd.MultiIndex.from_tuples(combs).to_series().apply(lambda t: f(*t))

关于python - Pandas 数据框每两行的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44190012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com