gpt4 book ai didi

python - 使用表合并数据框

转载 作者:行者123 更新时间:2023-11-30 22:53:08 24 4
gpt4 key购买 nike

我有一个相似度矩阵(它是作为数据框构建的):

mat = pd.DataFrame(index = df.a.values,columns = df.a.values)
mat[:] = [[1,0.2,0.3],[0.7,1,0.6],[0,0.4,1]]
id1 id2 id3
id1 1.0 0.2 0.3
id2 0.7 1.0 0.6
id3 0.0 0.4 1.0

我想创建另一个包含相同索引的数据框,但有一列包含最接近的id:

    id      closest
0 id1 id3
1 id2 id1
2 id3 id2

这个想法是在相似度矩阵的每一行中查找第二高值(对角线上的第一个值始终为 1),并检索相应列的名称。

我知道我可以将对角线设置为零,然后使用如下所示的内容:

def closest(x):
return np.where(x == x.max())

temp = mat.apply(lambda x: closest(x))
df['closest'] = df.index[[w[0][0] for w in temp.values]].tolist()

但是我找不到如何在不重新分配对角线的情况下过滤它..

注意:我的矩阵中的值都在0和1之间,唯一的1在对角线上

最佳答案

减去单位矩阵,然后使用DataFrame.idxmax()查找每行中最大值的索引。

import numpy as np
import pandas as pd

index = ['id1', 'id2', 'id3']
mat = pd.DataFrame([[1, 0.2, 0.3],[0.7, 1, 0.6],[0, 0.4, 1]],
index=index, columns=index)

(mat - np.identity(3)).idxmax(axis=1)

输出:

id1    id3
id2 id1
id3 id2
dtype: object

关于python - 使用表合并数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38305519/

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