首页 > 解决方案 > 在 Pandas Dataframe 上使用 groupby 按一列重新排列,最大值仅为另一列

问题描述

我试着用我的原始数据和代码来问这个问题,但我意识到它可能读起来太多了,所以我将尝试创建一些玩具数据来简化问题。这是带有一些玩具数据的代码,应该很容易复制/粘贴以重现:

import pandas as pd

df = pd.DataFrame([['A boy ran.', [1,2], 1, [5,7], 0.997], ['A good pet.', [7,9], 0, [3,2], 0.977], ['The car is fast.', [7,5], 1, [1,9], 0.962], ['The girl sang.', [0,5], 2, [4,1], 0.992]], columns=['sentences', 'embeddings', 'labels', 'cluster_centres', 'cosine_scores'])
print(df)

new_df = df.groupby(['labels']).max()
print(new_df)

初始数据框(df_ _并在每一行中包含一个浮点数。sentencesembeddingscluster_centreslabelscosine_scores

我想按列中的值对行进行分组labels(因此 0s 和 1s 和 2s 在一起),然后从每个标签sentence的列中具有最大值的行中的列中获取句子。cosine_scores所以为了澄清,在上面的例子中,列中有两行值为 1 labels。第一行(行索引=0)比另一行(行索引=2)具有更高的 cosine_score(具体而言:0.997>0.962)。因此,对于 1 的标签,我想要 index=0 ( 'A boy ran.') 中的句子。但是,当我运行上面的代码时,我得到以下数据框new_df

               sentences embeddings cluster_centres  cosine_scores
labels                                                            
0            A good pet.     [7, 9]          [3, 2]          0.977
1       The car is fast.     [7, 5]          [5, 7]          0.997
2         The girl sang.     [0, 5]          [4, 1]          0.992

如您所见,它为标签 = 1 的 cosine_scores 选择了正确的最大值(从行索引 = 0 为 0.997),但是,在句子列中它选择了错误的句子(应该是A boy ran而不是The car is fast)。根据我对实际数据的分析,这是因为它选择了以“max”字母开头的句子(即按字母顺序排列的字母,在这种情况下,T 在 A 之后,所以选择了另一个句子)。无论如何,所以我的问题是,我该如何选择 ONLY cosine_scores 的最大值并从同一行返回其他列作为每个标签的最大值labels?谢谢你的帮助!!

标签: pythonpandasdataframe

解决方案


根据标签和 cosine_scores 排序,并应用 drop_duplicates

df.sort_values(['labels', 'cosine_scores'], ascending=False).drop_duplicates(['labels'])

给出以下输出

        sentences embeddings  labels cluster_centres  cosine_scores
3  The girl sang.     [0, 5]       2          [4, 1]          0.992
0      A boy ran.     [1, 2]       1          [5, 7]          0.997
1     A good pet.     [7, 9]       0          [3, 2]          0.977

推荐阅读