Python 如何筛选属于具有多个成员的组的所有行?
我有一个和你一样的问题 我有这样一个数据帧:Python 如何筛选属于具有多个成员的组的所有行?,python,pandas,select,dataframe,group-by,Python,Pandas,Select,Dataframe,Group By,我有一个和你一样的问题 我有这样一个数据帧: 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
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
我想groupby
列B
和C
,然后从df
中选择组大小大于1的所有行
我的期望结果是
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
所以我能做到
gs_bool = df.groupby(['B', 'C']).size() > 1
给
B C
a x True
b x True
y False
c z True
dtype: bool
现在如何将此信息反馈给
df
你真的很接近-需要:
你真的很接近-需要:
IIUC: IIUC:
@jezrael,速度慢得多吗?@jezrael,是的,对于700.000行DFI发现它-,速度大约慢1.8倍。但这取决于群体的规模——第一,许多群体的gad时间不同,第二,较少群体的gad时间更好@jezrael,速度慢得多吗?@jezrael,是的,对于700.000行DFI发现它-,速度大约慢1.8倍。但这取决于群体的规模——第一,许多群体的gad时间不同,第二,较少群体的gad时间更好
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
In [38]: df.groupby(['B','C']).filter(lambda x: len(x) > 1)
Out[38]:
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