首页 > 解决方案 > 熊猫 groupby 和计数,如果计数减少删除组和剩余的添加新数据帧

问题描述

我想将数据分成 10 分钟的片段,如果少于 2 行删除组并计算行数并将剩余组合并到一个数据框中。

我已经尝试过了,但不确定如何删除行数少于 2 的组

df=pd.DataFrame({'x1':[5,5,4,6,1],'x2':[5,5,6,7,1],
                         'time':['11/7/2019 10:11','11/7/2019 10:14',
                                 '11/7/2019 10:16','11/7/2019 11:20',,'11/7/2019 11:27']}) 

df = df.set_index(pd.DatetimeIndex(df['time']))

x=df.groupby(pd.Grouper(freq='10Min', base=30, label='right')).count()

注意:我知道使用循环方法,我不想使用 for 循环

跟踪输出:

df1=pd.DataFrame({'x1':[5,5,4],'x2':[5,5,6],
                             'time':['11/7/2019 10:11','11/7/2019 10:14',
                                     '11/7/2019 10:16']}) 

标签: python-3.xpandasnumpypandas-groupby

解决方案


IIUC,您可以使用filter

grouped = df.groupby(pd.Grouper(freq='10Min', label='right'))
res = grouped.filter(lambda x: len(x) > 2)
print(res)

输出

                     x1  x2             time
time                                        
2019-11-07 10:11:00   5   5  11/7/2019 10:11
2019-11-07 10:14:00   5   5  11/7/2019 10:14
2019-11-07 10:16:00   4   6  11/7/2019 10:16

作为旁注,base参数已被弃用,在您的情况下,您不需要它。从文档中:

1.1.0 版后已弃用:您应该使用的新参数是“偏移”或“原点”。


推荐阅读