Python:在计数条件下删除行 [英] Python: Removing Rows on Count condition
本文介绍了Python:在计数条件下删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在过滤pandas
数据帧时遇到问题.
I have a problem filtering a pandas
dataframe.
city
NYC
NYC
NYC
NYC
SYD
SYD
SEL
SEL
...
df.city.value_counts()
我想删除计数频率低于4的城市行,例如SYD和SEL.
I would like to remove rows of cities that has less than 4 count frequency, which would be SYD and SEL for instance.
如果不按城市逐个手动删除它们,该怎么办?
What would be the way to do so without manually dropping them city by city?
推荐答案
在这里使用过滤器
df.groupby('city').filter(lambda x : len(x)>3)
Out[1743]:
city
0 NYC
1 NYC
2 NYC
3 NYC
解决方案二transform
sub_df = df[df.groupby('city').city.transform('count')>3].copy()
# add copy for future warning when you need to modify the sub df
这篇关于Python:在计数条件下删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文