【发布时间】:2021-11-04 12:34:12
【问题描述】:
我有一个包含 3 个目标类的数据集:“是”、“也许”和“否”。
Unique_id target
111 Yes
111 Maybe
111 No
112 No
112 Maybe
113 No
我想根据 unique_id 删除重复的行。但是“删除重复”通常保留第一行或最后一行,我想根据以下条件保留行:
1) If unique_id has all the 3 classes (Yes, Maybe and No), we’ll keep only the ‘Yes’ class.
2) If unique_id has the 2 classes (Maybe and No), we’ll keep only the ‘Maybe’ class.
3) We’ll keep the ‘No’ class when only ‘No’ will be there.
我尝试了“sort_values”目标类(Yes=1、Maybe=2、No=3),然后删除了重复项。
期望的输出:
Unique_id target
111 Yes
112 Maybe
113 No
我正在考虑是否有更好的方法来做到这一点。
任何建议将不胜感激。谢谢!
【问题讨论】:
-
如果我理解你使用整数值 1,2,3 而不是字符串,排序和删除。我认为没关系。一个非常相似的解决方案是使用categorical data 和
ordered=True。您也可以进行 groupby 并取最小值(1,2,3 之间) -
ID 中的所有行都具有该目标或只是任何一个?
-
看看您是否需要从下面的答案中进一步澄清。如果没有更多问题,请接受您选择的答案,让我们知道最适合您需求的任何答案。谢谢!
标签: python pandas dataframe data-manipulation drop-duplicates