【发布时间】:2022-01-15 08:11:20
【问题描述】:
我有一个数据集,其中作者按作者顺序(1、2、3 等)排名。
Authorid Author Article Articleid Rank
1 John article 1 1 1
1 John article 2 2 2
1 John article 3 3 3
1 John article 4 4 3
2 Mary article 5 5 1
2 Mary article 6 6 2
2 Mary article 7 7 1
2 Mary article 8 8 8
我想再创建三个布尔列If_first、If_second、If_last。
这样做的目的 - 我想显示作者在文章中的排名是第 1 位、第 2 位还是最后一位。
last 表示Rank 列中的最大数量(Rank 列中此Authorid 的最大数量)。
If_first 和If_second 可以,这很简单,但不知道如何解决If_last。
df.loc[df['Rank'] == 1, 'If_first'] = 1
df.loc[df['Rank'] != 1, 'If_first'] = 0
df.loc[df['Rank'] == 2, 'If_second'] = 1
df.loc[df['Rank'] != 2, 'If_second'] = 0
这里有两条规则
-
If_first=if_last- 把他当作if_first -
If_second=if_last- 把他当作if_second
预期输出:
Authorid Author Article Articleid Rank If_first If_second If_last
1 John article 1 1 1 1 0 0
1 John article 2 2 2 0 1 0
1 John article 3 3 3 0 0 1 (third is the last here)
2 Mary article 5 5 1 1 0 0
2 Mary article 6 6 2 0 1 0
2 Mary article 7 7 3 0 0 0 (third is not the last here, because of the fourth below, all zeros)
2 Mary article 8 8 4 0 0 1 (fourth is the last here)
【问题讨论】:
-
示例数据中是否有多余的行? Authorid 中的最后一个 == 1?它在您的输出中不存在。或者,如果在同一个 Authorid 中有相同排名的行,我们是否必须删除其中一行?
-
@sophocles,我再次更新了输出。如果 1,2,3 作者不是最后一个 - 那么所有值都必须为零。不知何故,我需要计算每个作者 ID 的最大 x 排名并将其分配给最后一个。希望对您有所帮助!