如何过滤所有属于超过1个成员的组的行? [英] How to filter all rows that belong to groups with more than 1 member?
本文介绍了如何过滤所有属于超过1个成员的组的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个和这个类似的问题。 p>
我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame({'A':list(range(7)),
'B':['a','b','a','c', 'c','b','b'],
'C':['x','x','x','z','z','y','x'] }
)
ABC
0 0 ax
1 1 bx
2 2 ax
3 3 cz
4 4 cz
5 5 by
6 6 bx
我想 groupby
columns B
和 C
,然后从<$ c $中选择所有行c> df 的组大小大于1。
我的期望结果为
ABC
0 0 ax
1 1 bx
2 2 ax
3 3 cz
4 4 cz
6 6 bx
所以我可以做 p>
gs_bool = df.groupby(['B','C'])。size()> 1
其中给出
BC
ax True
bx True
y False
cz True
dtype:bool
现在我如何回馈给 df
?
解决方案
你真的很接近 - 需要 GroupBy.transform
:
gs_bool = df.groupby(['B','C'])['B']。transform('size')> 1
print(gs_bool)
0 True
1 True
2 True
3 True
4 True
5 False
6 True
名称:B,dtype:bool
< pre $
df = df [gs_bool]
print(df)
ABC
0 0 ax
1 1 bx
2 2 ax
3 3 cz
4 4 cz
6 6 bx
I have a similar question as this one.
I have a dataframe like this:
import pandas as pd
df = pd.DataFrame({'A': list(range(7)),
'B': ['a', 'b', 'a', 'c', 'c', 'b', 'b'],
'C': ['x', 'x', 'x', 'z', 'z', 'y', 'x']}
)
A B C
0 0 a x
1 1 b x
2 2 a x
3 3 c z
4 4 c z
5 5 b y
6 6 b x
I want to groupby
columns B
and C
and then select all rows from df
that have a group size greater than 1.
My desired outcome would be
A B C
0 0 a x
1 1 b x
2 2 a x
3 3 c z
4 4 c z
6 6 b x
So I can do
gs_bool = df.groupby(['B', 'C']).size() > 1
which gives
B C
a x True
b x True
y False
c z True
dtype: bool
How do I now feed this back to df
?
解决方案
You are really close - need GroupBy.transform
:
gs_bool = df.groupby(['B', 'C'])['B'].transform('size') > 1
print (gs_bool)
0 True
1 True
2 True
3 True
4 True
5 False
6 True
Name: B, dtype: bool
df = df[gs_bool]
print (df)
A B C
0 0 a x
1 1 b x
2 2 a x
3 3 c z
4 4 c z
6 6 b x
这篇关于如何过滤所有属于超过1个成员的组的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文