3 回答

TA贡献1789条经验 获得超8个赞
您可以使用len:
In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
In [12]: df.groupby('A').filter(lambda x: len(x) > 1)
Out[12]:
A B
0 1 2
1 1 4

TA贡献1831条经验 获得超10个赞
行数在属性中.shape[0]
:
df.groupby('A').filter(lambda x: x.shape[0] >= min_size)
注意:如果要删除小于最小尺寸的组,请保留大于或处于最小尺寸(>=
,不是>
)的组。

TA贡献1818条经验 获得超7个赞
groupby.filter对于较大的数据集/大量组,可能会非常慢。更快的方法是使用groupby.transform:
下面是一个例子,首先创建数据集:
import pandas as pd
import numpy as np
df = pd.concat([
pd.DataFrame({'y': np.random.randn(np.random.randint(1,5))}).assign(A=str(i))
for i in range(1,1000)
]).reset_index(drop=True)
print(df)
y A
0 1.375980 1
1 -0.023861 1
2 -0.474707 1
3 -0.151859 2
4 -1.696823 2
... ... ...
2424 0.276737 998
2425 -0.142171 999
2426 -0.718891 999
2427 -0.621315 999
2428 1.335450 999
[2429 rows x 2 columns]
计时:
添加回答
举报