【问题标题】:How to find second max from pandas dataframe (cosine similarity matrix)如何从熊猫数据框中找到第二个最大值(余弦相似度矩阵)
【发布时间】:2015-09-04 23:38:24
【问题描述】:

如何从 pandas 数据帧(余弦相似度矩阵)中找到 index!=column 的第二个最大值或最大值?我可以遍历每一列并执行 index!=column 但我确信有更好的方法...

import pandas as pd
cos = pd.DataFrame([
    [ 1.        ,  0.17404038,  0.36849397],
    [ 0.17404038,  1.        ,  0.20505339],
    [ 0.36849397,  0.20505339,  1.        ]
    ])
cos.columns = ['A', 'B', 'C']
cos.index = ['A', 'B', 'C']

cos 是这样的

    A           B           C
A   1.000000    0.174040    0.368494
B   0.174040    1.000000    0.205053
C   0.368494    0.205053    1.000000

排除值为 1 的单元格,我希望结果为

    Col1    Col2
0   A       C
1   B       C
2   C       A

我可以这样做并获得第二个最大值而不是最大值吗?

results = cos.idxmax().reset_index()
results.columns = ['Col1', 'Col2']

results
    Col1    Col2
0   A       A
1   B       B
2   C       C

【问题讨论】:

  • 为什么不直接将1 设置为-1,然后得到max

标签: pandas max cosine-similarity


【解决方案1】:

您可以将1 替换为任意值,然后像以前一样调用idxmaxreset_index

In [140]:
cos.replace(1,np.NaN).idxmax().reset_index()

Out[140]:
  index  0
0     A  C
1     B  C
2     C  A

所以只是为了让事情变得更糟:

In [141]:
new_df = cos.replace(1,np.NaN).idxmax().reset_index()
new_df.columns=['Col1', 'Col2']
new_df

Out[141]:
  Col1 Col2
0    A    C
1    B    C
2    C    A

更新

如果要添加值,则可以调用apply 并使用new_df 值从cos df 执行查找:

In [144]:
new_df['value'] = new_df.apply(lambda x: cos.loc[x['Col1'], x['Col2']], axis=1)
new_df

Out[144]:
  Col1 Col2     value
0    A    C  0.368494
1    B    C  0.205053
2    C    A  0.368494

其实你可以使用lookup:

In [146]:
new_df['value'] = cos.lookup(new_df['Col1'], new_df['Col2'])
new_df

Out[146]:
  Col1 Col2     value
0    A    C  0.368494
1    B    C  0.205053
2    C    A  0.368494

【讨论】:

  • 啊,太好了!我没有考虑到这一点。谢谢!
  • 对不起,还有一个问题,您如何将匹配值添加到 new_df 的新列?即我想看到第一行的 A、C、0.368494
【解决方案2】:

为什么不使用 rank 方法来获取所有列的排名?

>>> ranking = cos.rank(ascending=False)
>>> ranking
   A  B  C
A  1  3  2
B  3  1  3
C  2  2  1

【讨论】:

  • 是的,那么我可以选择所有带有 2 的行。
  • 或 3,或 4,或任何您需要的值。 :) 另外,它不需要您更改数据...
猜你喜欢
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 2015-07-17
  • 2019-12-23
  • 2021-08-20
  • 2021-06-30
相关资源
最近更新 更多