首页 > 解决方案 > 在 Pandas 数据框中按其他列分组的列中删除频率最低的行

问题描述

我有一个行不一致的熊猫数据框。在下面的示例中,and是两个放在一起的值必须是唯一的,因此这对是主键,应该在数据框中出现一次,而是 and的二进制信息,可以是or 。不幸的是,在数据框中重复,有时它们有,而其他时候,这显然是一个错误。key1key2(key1 ,key2)info(key1 ,key2)TF(key1 ,key2)info=Tinfo=F

为了消除重复,我想采用这种推理:我想计算(对于同一对夫妇(key1 ,key2)info有多少次,有T多少次infoF

  1. 如果频率不同(大部分时间),则只保留具有最频繁值的行之一,并且T 具有F类似的函数df.drop_duplicates(subset = ["key1","key2"] , keep = "first"),其中first应该是最频繁值的行info
  2. 如果相反 50% 的行有info=T50% 有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

谢谢

标签: pythonpandasdataframeduplicates

解决方案


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.

推荐阅读