Skip to main content
 首页 » 编程设计

python之Pandas 选择根计数 3 次的行

2025年05月04日13grandyang

举个例子:

df = pd.DataFrame({ 
    'file':['f1','f2','f3','f4','f5','f6','f7','f8','f9','f10','f11','f12'], 
    'root':['root1','root1','root1','root2','root2','root2','root3','root4','root5','root6','root6','root6'], 
}) 
 

我需要这样的输出:

    file    root 
0   f1  root1 
1   f2  root1 
2   f3  root1 
3   f4  root2 
4   f5  root2 
5   f6  root2 
9   f10 root6 
10  f11 root6 
11  f12 root6 
 

因为 root1/root2/root3 在列中计数 3 次

请您参考如下方法:

filter

此 API 是 groupby 对象的 filter 方法。
see also Split-Apply-Combine

df.groupby('root').filter(lambda x: x.size > 2) 
 
   file   root 
0    f1  root1 
1    f2  root1 
2    f3  root1 
3    f4  root2 
4    f5  root2 
5    f6  root2 
9   f10  root6 
10  f11  root6 
11  f12  root6 

将一个可调用对象传递给 filter,它接受一个数据框作为参数并返回一个 bool 值。 groupby 然后仅返回那些可调用返回 True

的组