python-3.x - 熊猫 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']})
解决方案
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 版后已弃用:您应该使用的新参数是“偏移”或“原点”。
推荐阅读
- php - 如何在 Laravel 中显示来自 public/storage/images 的图像
- vue.js - 如果一旦逻辑为真,Vue总是显示组件
- huggingface-transformers - 在使用 HuggingFace 的 RobertaTokenizer 之前,我是否需要先对文本进行预标记?(不同的理解)
- mysql - SQL 查询以查找遵循特定模式的字符串
- selenium - Selenium 自动化:根据@BeforeMethod 中的条件跳过测试的执行
- ios - 如何在 iOS 中获取附近运营商 (GSM) 的列表和信息
- installation - 包安装问题,(生存分析)
- javascript - 将图像从画布保存到服务器。空白图像被保存
- angular - Highchart - 双轴折线图问题
- swiftui - 具有 UIViewcontrollerRepresentable 的自定义 UIViewController 具有在 SwiftUI 中调用时崩溃或为零的 UITextView