让
import pandas as pd
df = pd.DataFrame(
{
'a': ['A', 'A', 'B', 'B', 'B', 'C'],
'b': [True, True, True, False, False, True]
}
)
print(df)
groups = df.groupby('a') # "A", "B", "C"
agg_groups = groups.agg({'b':lambda x: all(x)}) # "A": True, "B": False, "C": True
agg_df = agg_groups.reset_index()
filtered_df = agg_df[agg_df["b"]] # "A": True, "C": True
print(filtered_df)
# Now I want to get back the original df's rows, but only the remaining ones after group filtering
电流输出:
a b
0 A True
1 A True
2 B True
3 B False
4 B False
5 C True
a b
0 A True
2 C True
必填:
a b
0 A True
1 A True
2 B True
3 B False
4 B False
5 C True
a b
0 A True
2 C True
a b
0 A True
1 A True
5 C True
df[df['a'].isin(filtered_df['a'].unique())]
结果:
a b
0 A True
1 A True
5 C True
GroupBy.transform
让所有Trues以与原始DataFrame相同的大小进行屏蔽,因此可以使用boolean indexing
:
df1 = df[df.groupby('a')['b'].transform('all')]
#alternative
#f = lambda x: x.all()
#df1 = df[df.groupby('a')['b'].transform(f)]
print (df1)
a b
0 A True
1 A True
5 C True
如果要在聚合函数输出中过滤是布尔系列,过滤匹配原始列映射的索引
a
:
ids = df.groupby('a')['b'].all()
df1 = df[df.a.isin(ids.index[ids])]
print (df1)
a b
0 A True
1 A True
5 C True
您的解决方案与过滤列类似
b
:
groups = df.groupby('a')
agg_groups = groups.agg({'b':lambda x: all(x)})
df1 = df[df.a.isin(agg_groups.index[agg_groups['b']])]
print (df1)
a b
0 A True
1 A True
5 C True