![](/img/trans.png)
[英]Delete Pandas Dataframe columns if there are zeros in more than K rows
[英]pandas dataframe delete groups with more than n rows in groupby
我有一个 dataframe:
df = [type1 , type2 , type3 , val1, val2, val3
a b q 1 2 3
a c w 3 5 2
b c t 2 9 0
a b p 4 6 7
a c m 2 1 8
a b h 8 6 3
a b e 4 2 7]
我想根据列 type1、type2 应用 groupby 并从 dataframe 中删除超过 2 行的组。 所以新的 dataframe 将是:
df = [type1 , type2 , type3 , val1, val2, val3
a c w 3 5 2
b c t 2 9 0
a c m 2 1 8
]
最好的方法是什么?
使用GroupBy.transform
获取与原始大小相同的Series
的组数,因此可以通过Series.le
过滤<=
在boolean indexing
中:
df = df[df.groupby(['type1','type2'])['type1'].transform('size').le(2)]
print (df)
type1 type2 type3 val1 val2 val3
1 a c w 3 5 2
2 b c t 2 9 0
4 a c m 2 1 8
如果性能不重要或很小 DataFrame 可以使用DataFrameGroupBy.filter
:
df =df.groupby(['type1','type2']).filter(lambda x: len(x) <= 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.