2017-08-11 69 views
1

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

例如在下表中。第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 

有,我可以为任意数量的列达到大熊猫或SQL(PostrgeSQL)这样的逻辑简单的方法是什么?

回答

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 
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 

希望它可以帮助

+0

谢谢,但是这不工作,当有更多的列,我已经给了一个例子很抱歉,如果我的问题一开始并不清楚 – user113531

+0

先生你对冗余数据的想法有点难以理解。你可以添加你想要的预期输出。 – Dark