Skip to main content
 首页 » 编程设计

python之Pandas 过滤大于 1 的唯一值并连接唯一值

2025年05月04日20qq78292959

我有一个 Pandas 数据框:

df2 = pd.DataFrame({'c':[1,1,1,2,2,2,2,3], 
                    'type':['m','n','o','m','m','n','n', 'p']}) 

我想找出 c 的哪些值具有不止一种唯一类型,对于那些返回 c 值的值、唯一类型的数量和所有唯一类型类型连接在一个字符串中。

到目前为止,我已经使用了这两个问题:

pandas add column to groupby dataframe Python Pandas: concatenate rows with unique values

df2['Unique counts'] = df2.groupby('c')['type'].transform('nunique') 
 
df2[df2['Unique counts'] > 1].groupby(['c', 'Unique counts']).\ 
                                  agg(lambda x: '-'.join(x)) 
 
Out[226]:  
                    type 
c Unique counts          
1 3                m-n-o 
2 2              m-m-n-n 

这可行,但我无法获得唯一值(例如,在第二行中,我希望只有一个 m 和一个 n。 我的问题如下:

  1. 我可以跳过创建“唯一计数”和 创造一些临时的东西?
  2. 如何过滤唯一值 在第二步?

请您参考如下方法:

首先删除唯一行然后计算值的解决方案 - 创建助手系列 s 并且对于唯一字符串使用 sets:

s= df2.groupby('c')['type'].transform('nunique').rename('Unique counts') 
a = df2[s > 1].groupby(['c', s]).agg(lambda x: '-'.join(set(x))) 
print (a) 
 
                  type 
c Unique counts        
1 3              o-m-n 
2 2                m-n 

另一个想法是先删除重复项 DataFrame.duplicated :

df3 = df2[df2.duplicated(['c'],keep=False) & ~df2.duplicated(['c','type'])] 
print (df3) 
 
   c type 
0  1    m 
1  1    n 
2  1    o 
3  2    m 
5  2    n 

然后使用 join 聚合计数:

a = df3.groupby('c')['type'].agg([('Unique Counts', 'size'), ('Type', '-'.join)]) 
print (a) 
   Unique Counts   Type 
c                       
1              3  m-n-o 
2              2    m-n 

或者如果需要先聚合所有值:

df4 = df2.groupby('c')['type'].agg([('Unique Counts', 'nunique'),  
                                  ('Type', lambda x: '-'.join(set(x)))]) 
print (df4) 
   Unique Counts   Type 
c                       
1              3  o-m-n 
2              2    m-n 
3              1      p 

最后通过 boolean indexing 删除唯一行:

df5 = df4[df4['Unique Counts'] > 1] 
print (df5) 
   Unique Counts   Type 
c                       
1              3  o-m-n 
2              2    m-n