保留数据框中的行,对于某些列的值的所有组合,在另一列中包含相同的元素

Keep rows in data frame that, for all combinations of the values of certain columns, contain the same elements in another column

df = pd.DataFrame({'a':['x','x','x','x','x','y','y','y','y','y'],'b':['z','z','z','w','w','z','z','w','w','w'],'c':['c1','c2','c3','c1','c3','c1','c3','c1','c2','c3'],'d':range(1,11)})

   a  b   c   d
0  x  z  c1   1
1  x  z  c2   2
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
8  y  w  c2   9
9  y  w  c3  10

对于 ab 的所有组合,如何只保留 c 中包含相同值的行?或者换句话说,如何排除具有 c 值且仅出现在 ab 的某些组合中的行?

例如,只有c1c3出现在ab的所有组合中([x,z][x,w][y,z],[y,w]), 所以输出为

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

如果您做出以下假设,这将告诉您要保留 c 列的哪些元素:

df.groupby("c")["a"].count() == df.groupby("c")["a"].count().max()

输出:

c
c1     True
c2    False
c3     True
Name: a, dtype: bool

假设:

  1. 没有重复项
  2. c 列至少有一个值包含 a 和 b 的所有组合。

这是一种方法。获取每个组的唯一列表,然后使用 reducenp.intersect1d 检查所有返回数组中的公共元素。然后使用 series.isinboolean indexing

过滤数据框
from functools import reduce
out = df[df['c'].isin(reduce(np.intersect1d,df.groupby(['a','b'])['c'].unique()))]

细分:

s = df.groupby(['a','b'])['c'].unique()
common_elements = reduce(np.intersect1d,s)
#Returns :-> array(['c1', 'c3'], dtype=object)

out = df[df['c'].isin(common_elements )]#.copy()

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

让我们尝试旋转 table,然后删除 NA,这意味着组合中缺少一个值:

all_data =(df.pivot(index=['a','b'], columns='c', values='c')
             .loc[:, lambda x: x.notna().all()]
             .columns)
df[df['c'].isin(all_data)]

输出:

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

让我们尝试 groupbynunique 来计算每列 c 组的唯一元素数:

s = df['a'] + ',' + df['b'] # combination of a, b
m = s.groupby(df['c']).transform('nunique').eq(s.nunique())

df[m]

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

您可以将列表理解与 str.contains 一起使用:

unq = [[x, len(df[(df[['a','b','c']].agg(','.join, axis=1)).str.contains(',' + x)]
                   .drop_duplicates())] for x in df['c'].unique()]
keep = [lst[0] for lst in unq if lst[1] == max([lst[1] for lst in unq])]
df = df[df['c'].isin(keep)]
df

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

我们可以使用 groupby + size 然后 unstack,这将为 ['a'、'b' 组填充 NaN ] 缺少 'c' 组。然后我们 dropna 并将原始 DataFrame 子集化为 c 在 dropna 中存活的值。

df[df.c.isin(df.groupby(['a', 'b', 'c']).size().unstack(-1).dropna(axis=1).columns)]

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

groupby 操作的结果仅包含 c 组的列,这些列存在于 ['a', 'b'] 的所有唯一组合中,所以我们只获取列属性。

df.groupby(['a', 'b', 'c']).size().unstack(-1).dropna(axis=1)

#c     c1   c3
#a b          
#x w  1.0  1.0
#  z  1.0  1.0
#y w  1.0  1.0
#  z  1.0  1.0

尝试不同的东西crosstab

s = pd.crosstab([df['a'],df['b']],df.c).all()
out = df.loc[df.c.isin(s.index[s])]
Out[34]: 
   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10

假设示例中有 4 个不同的值:

一个简单的解决方案可以是:

df[df['a'].groupby(df['c']).transform('count').eq(4)]

您可以使用 value_counts 并获得 ab 的所有组合:

vc = df[['a', 'b']].drop_duplicates().value_counts()

结果:

a  b
y  z    1
   w    1
x  z    1
   w    1

然后您可以比较具有缺失组合的 vcfilter 每个组的计数:

df.groupby('c').filter(lambda x: x[['a', 'b']].value_counts().ge(vc).all())

输出:

   a  b   c   d
0  x  z  c1   1
2  x  z  c3   3
3  x  w  c1   4
4  x  w  c3   5
5  y  z  c1   6
6  y  z  c3   7
7  y  w  c1   8
9  y  w  c3  10