簡體   English   中英

如何過濾成員多於1個的組中的所有行?

[英]How to filter all rows that belong to groups with more than 1 member?

我有一個類似的問題,因為這一個

我有一個這樣的數據框:

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

我想groupbyBC ,然后選擇從所有的行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

您真的很親密-需要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

IIUC:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM