首页 > 解决方案 > 排序、排名、groupby 和 sum 组合 -> Python pandas

问题描述

我有一个带有段落对的熊猫数据框。大约有 500 个段落,每个段落按以下格式列出(按段落 A 排序并按最高预测排名):

ParagraphA | paragraphB | label | prediction

Paragraph1 | Pragraph2  | 1 ----| 0.9890


Paragraph1 | Pragraph10  | 1 ----| 0.9870


Paragraph1 | Pragraph17  | 0 ----| 0.9860


Paragraph1 | Pragraph34  | 1 ----| 0.9820

我已经对此进行了排序和分组(之前段落和预测是随机顺序的):

sorted_grouped = df.sort_index(by=['paragraphA', 'predictions'], ascending=[True, False])

这是一个排名问题,我试图预测段落之间存在链接的可能性。我现在想根据实际存在的链接数量来测量精度(参见“标签”)。

我将如何计算每个段落(在段落A下)标签下的“1”数量以及这些“1”出现在前 x 个结果中的次数?(x 是基于该段落的“1”总数。如果有七个“1”,我会查看前七个结果)

对于我上面的示例,假设在 Paragraph1 的标签下总共有三个“1”,但在前三个中,只有两个“1”。

因此,我想提取该信息:

1) 总分 1 = 3

2) 1 在前 3 = 2

标签: pythonpandassortinggrouping

解决方案


我不明白“标签”列是否只有数字,或者条目是否像显示的那样(即'1 ----')。在这种情况下,我建议首先以这种方式创建一个新列:

df['new_label'] = df['label'].astype(str).str[0]
df['new_label'] = df['new_label'].astype(int)

如果 'label' 列已经只填充了数字,则忽略此段落,并在下面使用 'label' 而不是 'new_label' (我还假设列 'new_label' 中的值只有 0 或 1):

 total = df.groupby('ParagraphA')['new_label'].sum() # this gives you the number of 1s
percentage = df.groupby('ParagraphA')['new_label'].apply(lambda g : g.head(g.sum()).sum() / g.sum()) # this gives you the percentage of 1s in the first x rows

推荐阅读