删除组

时间:2017-08-11 03:34:30

标签: postgresql pandas group-by duplicates

我想删除每个组(在本例中为datasource)中数据库中的冗余行,我将其定义为包含严格少于其他行的信息或信息的行。

例如,在下表中。第1行是冗余的,因为同一组中的另一行第0行包含与其完全相同的信息,但包含更多数据。

出于同样的原因,第6行是冗余的,组中的所有其他行3,4和5包含更多信息。但是我保留了第4行和第5行,因为它们与组中的其他行有一些额外的不同信息。

   datasource         city country
0           1    Shallotte      US
1           1         None      US
2           2       austin      US
3           3  Casselberry      US
4           3         None      AU
5           3  Springfield    None
6           3         None    None

当有更多列时,行0和1,4是不同的信息。但是,第2行和第3行(或第1行)包含冗余信息。

  datasource         city country   Count
0           1        None       US     11
1           1       austin    None   None
2           1        None     None     11
3           1       austin    None   None
4           1        None       CA   None

预期输出

  datasource         city country   Count
0           1        None       US     11
1           1       austin    None   None
4           1        None       CA   None

有没有一种简单的方法可以在pandas或SQL(PostrgeSQL)中为任意数量的列实现这样的逻辑?

2 个答案:

答案 0 :(得分:1)

其中一种方法是基于无计数并删除最大无值的行,即

#Count the None values across the row
df['Null'] = (df.values == 'None').sum(axis=1)

#Get the maximum of the count based on groupby
df['Max'] = df.groupby('datasource')['Null'].transform(max)

# Get the values are not equal to max and  equal to zero and drop the columns
df = df[~((df['Max'] !=0) & (df['Max'] == df['Null']))].drop(['Null','Max'],axis=1)

输出:

  datasource         city country
0           1    Shallotte      US
2           2       austin      US
3           3  Casselberry      US
4           3         None      AU
5           3  Springfield    None

希望有所帮助

答案 1 :(得分:1)

这是采用与Bharath shetty解决方案相同的基本策略的不同方法。这种感觉对我来说有点整洁。

首先,构建示例数据框:

import pandas as pd
data = {"datasource": [1,1,2,3,3,3,3],
        "city": ["Shallotte", None, "austin", "Casselberry", None, "Springfield", None],
        "country": ["US", "US", "US", "US", "AU", None, None]}
df = pd.DataFrame(data)

df['null'] = df.isnull().sum(axis=1)

print(df)
          city country  datasource  null
0    Shallotte      US           1     0
1         None      US           1     1
2       austin      US           2     0
3  Casselberry      US           3     0
4         None      AU           3     1
5  Springfield    None           3     1
6         None    None           3     2

现在使用groupbyapply制作一个布尔掩码 - 我们只删除每组的最大空值:

def null_filter(d):
    if len(d) > 1:
        return d.null < d.null.max()
    return d.null == d.null

mask = df.groupby("datasource").apply(null_filter).values

df.loc(mask).drop("null", 1)

输出:

             city country  datasource
0    Shallotte      US           1
2       austin      US           2
3  Casselberry      US           3
4         None      AU           3
5  Springfield    None           3
相关问题