You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为重复数据DataFrame新增列:标记相似度最大值行为True其余为False

Pandas实现分组标记相似度最大值行

原始数据结构

初始DataFrame结构如下:

index  Key_words_x       Similarity    Label
0      0      embarker          0.996412  INVESTMENT
1      1      embarkest         0.996413  INVESTMENT
2      2      embarketh         0.996418  INVESTMENT
3      3      negative gearing  0.996215  INVESTMENT
4      4      overfinance       0.996215  INVESTMENT
...    ...     ...              ...       ...
7521   7521   crowded           0.340883  LOCATION
7522   7522   nanjing           0.337241  LOCATION
7523   7523   vibrant           0.336480  LOCATION
7524   7524   sprawl            0.335916  LOCATION
7525   7525   flourishing       0.333760  LOCATION

需求

新增Result列,将每个Label分组中Similarity值最大的行标记为True,其余行标记为False。

解决方案

方法一:批量标记所有最大值行

该方法会把分组内所有相似度等于最大值的行都标记为True:

import pandas as pd

# 假设你的DataFrame变量名为df
df['Result'] = df.groupby('Label')['Similarity'].transform(lambda x: x == x.max())

方法二:仅标记第一个出现的最大值行

如果同一分组存在多个相同的最大值,该方法只标记第一个出现的那一行:

# 获取每个Label分组中相似度最大值对应的行索引
max_row_indices = df.groupby('Label')['Similarity'].idxmax()
# 匹配索引标记结果
df['Result'] = df.index.isin(max_row_indices)

处理后结果示例

index  Key_words_x       Similarity    Label      Result
0      0      embarker          0.996412  INVESTMENT  False
1      1      embarkest         0.996413  INVESTMENT  False
2      2      embarketh         0.996418  INVESTMENT  True
3      3      negative gearing  0.996215  INVESTMENT  False
4      4      overfinance       0.996215  INVESTMENT  False
...    ...     ...              ...       ...        ...
7521   7521   crowded           0.340883  LOCATION    True
7522   7522   nanjing           0.337241  LOCATION    False
7523   7523   vibrant           0.336480  LOCATION    False
7524   7524   sprawl            0.335916  LOCATION    False
7525   7525   flourishing       0.333760  LOCATION    False

内容的提问来源于stack exchange,提问作者Thiru 8184

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:18:18