python - 在 Pandas 数据框中按其他列分组的列中删除频率最低的行
问题描述
我有一个行不一致的熊猫数据框。在下面的示例中,and是两个放在一起的值必须是唯一的,因此这对是主键,应该在数据框中出现一次,而是 and的二进制信息,可以是or 。不幸的是,在数据框中重复,有时它们有,而其他时候,这显然是一个错误。key1
key2
(key1 ,key2)
info
(key1 ,key2)
T
F
(key1 ,key2)
info=T
info=F
为了消除重复,我想采用这种推理:我想计算(对于同一对夫妇(key1 ,key2)
)info
有多少次,有T
多少次info
是F
和
- 如果频率不同(大部分时间),则只保留具有最频繁值的行之一,并且
T
具有F
类似的函数df.drop_duplicates(subset = ["key1","key2"] , keep = "first")
,其中first
应该是最频繁值的行info
。 - 如果相反 50% 的行有
info=T
50% 有info=F
,我想删除所有这些,因为我不知道哪个是正确的具有类似df.drop_duplicates(subset = ["key1","key2"] , keep = False)
.
我不知道如何进行这种过滤器,因为我想在一种情况下保留 1 行,在另一种情况下保留 0 行,具体取决于相似行组中特定列的值。
期望的行为
在:
key1 key2 info
0 a1 a2 T
1 a1 a2 T #duplicated row of index 0
2 a1 a2 F #similar row of indexes 0 and 1 but inconsistent with info field
3 b1 b2 T
4 b1 b2 T #duplicated row of index 3
5 b1 b3 T #not duplicated since key2 is different from indexes 3 and 4
6 c1 c2 T
7 c1 c2 F #duplicated row of index 5 but inconsistent with info field
出去:
key1 key2 info
0 a1 a2 T # for(a1,a2) T:2 and F:1
3 b1 b2 T # for(b1,b2) T:2 and F:0
5 b1 b3 T # for(b1,b3) T:1 and F:0
# no rows for (c1,c2) because T:1 and F:1
谢谢
解决方案
groupby
并用于pd.Series.mode
获取模态值。pd.Series.mode
将返回 ties 的情况下的模式,因此这允许我们删除这些情况,drop_duplicates
因为我们期望每个唯一的只有一个模式['key1', 'key2']
。
import pandas as pd
(df.groupby(['key1', 'key2'])['info']
.apply(pd.Series.mode)
.reset_index()
.drop_duplicates(['key1', 'key2'], keep=False)
.drop(columns='level_2')
)
# key1 key2 info
#0 a1 a2 T
#1 b1 b2 T
#2 b1 b3 T
groupby
+的结果mode
是:
key1 key2
a1 a2 0 T
b1 b2 0 T
b3 0 T
c1 c2 0 F # Tied mode so it gets 2 rows with the last
1 T # index level indicating the # of items tied for mode.
推荐阅读
- python - Pandas 以特殊字符分隔的分组和求和数据列
- javascript - Google App Script 中是否有不同的 Javascript 对象?
- javascript - 用鼠标单击捕获元素后取消放置事件
- javascript - 如果tinymce.get()中的id如何触发类而不是
- c# - Entity Framework Core 3.1 嵌套集合删除对象 Linq 表达式失败
- amazon-web-services - AWS 环境变量替换
- react-native - 用户导航到新屏幕时组件未卸载
- azure-devops - 在 Azure DevOps 中开始新构建时可以知道更新的文件
- vue.js - 如何提供要替换的组件
与属性? - node.js - 需要刷新令牌时如何暂停和恢复?