是否有熊猫函数来计算时间戳之间的事件?

如何解决是否有熊猫函数来计算时间戳之间的事件?

我的数据只有10万行和以下列:

  1. Time(yyyy-MM-dd hh:mm:ss.ffffff),
  2. ID(字符串)
  3. Group1(int32),
  4. Group2(int32)。

在5分钟的时间范围内,我想计算出每个事件之前来自同一Group1Group2的事件数。 例如:

ID              Time                      Group1    Group2
61ED2269CCAC    2020-07-27 00:01:05.781   1234      100123
61C2DC4E96FA    2020-07-27 00:01:17.279   1234      100123
FAD0839C1A95    2020-07-27 00:02:38.112   1234      100124
A2750A7B6C24    2020-07-27 00:16:50.592   4321      100123
03F5DF150A3C    2020-07-27 00:17:00.246   4321      100124

Timestamp('2020-07-26 23:56:17.279000')之后(第二个事件之前5分钟)发生了多少个事件,它们属于Group1Group2组?因此,在此示例中,第二个事件的计数器为1。其余的将是0,因为它们的组是唯一的。

每个事件都应有一个计数器,以指示在同一组中发生了多少事件。

我尝试按组和Time对数据进行排序,然后运行一个嵌套循环,一个在所有事件上运行,一个从开始到当前事件索引运行。在几千行之后,该过程将显着减慢速度,从而使该选项不可行。 我想知道是否还有其他优雅有效的方法。

编辑: 我能够使用一个for循环而不是嵌套的循环来做到这一点。对于每个循环,我都将时间和组分开,并对数据帧进行切片,以将事件包括在组中和所需的时间范围内,然后将事件总数相加:

for i in tqdm(range(len(df))):
   time_stamp = df.loc[i,'Time']
   group1 = df.loc[i,'Group1']
   group2 = df.loc[i,'Group2']
   sub_df = df[df['Time'] + timedelta(minutes=-5) > time_stamp]
   sub_df = sub_df[sub_df['Time'] < time_stamp]
   sub_df = sub_df[sub_df['Group1'] == group1]
   sub_df = sub_df[sub_df['Group2'] == group2]
   df.loc[i,'prior_events'] = sub_df.size

尽管如此,tqdm每秒显示18次迭代,对于10万行来说并没有那么大。

解决方法

为了获得更具启发性的结果,我扩展了您的数据样本:

              ID                    Time  Group1  Group2
0   61ED2269CCAC 2020-07-27 00:01:05.781    1234  100123
1   61C2DC4E96FA 2020-07-27 00:01:17.279    1234  100123
2   FAD0839C1A95 2020-07-27 00:02:38.112    1234  100124
3   FAD0839C1A95 2020-07-27 00:05:38.000    1234  100123
4   FAD0839C1A95 2020-07-27 00:06:39.000    1234  100123
5   A2750A7B6C24 2020-07-27 00:16:50.592    4321  100123
6   03F5DF150A3C 2020-07-27 00:17:00.246    4321  100124
7   03F5DF150A3C 2020-07-27 00:18:00.000    4321  100124
8   03F5DF150A3C 2020-07-27 00:20:00.000    4321  100124
9   03F5DF150A3C 2020-07-27 00:22:00.000    4321  100124
10  03F5DF150A3C 2020-07-27 00:23:00.000    4321  100124

假设 Time 列为 datetime 类型,并且其值是唯一的, 您可以按以下方式生成结果( Count 列):

df.set_index('Time',inplace=True)
df['Count'] = (df.groupby(['Group1','Group2'],as_index=False)\
    .Group1.rolling(window='5T',closed='both').count() - 1).astype(int)\
    .reset_index(level=0,drop=True)
df.reset_index(inplace=True)

结果是:

                      Time            ID  Group1  Group2  Count
0  2020-07-27 00:01:05.781  61ED2269CCAC    1234  100123      0
1  2020-07-27 00:01:17.279  61C2DC4E96FA    1234  100123      1
2  2020-07-27 00:02:38.112  FAD0839C1A95    1234  100124      0
3  2020-07-27 00:05:38.000  FAD0839C1A95    1234  100123      2
4  2020-07-27 00:06:39.000  FAD0839C1A95    1234  100123      1
5  2020-07-27 00:16:50.592  A2750A7B6C24    4321  100123      0
6  2020-07-27 00:17:00.246  03F5DF150A3C    4321  100124      0
7  2020-07-27 00:18:00.000  03F5DF150A3C    4321  100124      1
8  2020-07-27 00:20:00.000  03F5DF150A3C    4321  100124      2
9  2020-07-27 00:22:00.000  03F5DF150A3C    4321  100124      3
10 2020-07-27 00:23:00.000  03F5DF150A3C    4321  100124      3

注意最后一行。是否具有 Count == 3 ,包括事件 5分钟前 如果您希望计算此事件,请删除 closed ='both' 参数。

根据14:49Z的评论进行编辑

很明显,即使在一个组中,您的数据也具有重复的 Time 值 具有相同 Group1 / Group2 的行。

要解决此问题,请采用另一种方法:

  1. 定义一个生成计数的函数:

     def Counts(grp):
         vc = grp.Time.value_counts().sort_index()
         cnt = (vc.rolling(window='5T',closed='both').sum()).astype(int) - vc
         s = pd.Series(cnt,index=grp.Time)
         return pd.Series(s.values,index=grp.index)
    
  2. 应用它:

     df['Counts'] = df.groupby(['Group1',as_index=False)\
         .apply(Counts).reset_index(level=0,drop=True)
    

此代码基于您的源DataFrame已排序的假设 通过 Time

我在数据样本上测试了上面的代码,并添加了重复的行 前一行的时间

结果是:

              ID                    Time  Group1  Group2  Counts
0   61ED2269CCAC 2020-07-27 00:01:05.781    1234  100123       0
1   61C2DC4E96FA 2020-07-27 00:01:17.279    1234  100123       1
2   FAD0839C1A95 2020-07-27 00:02:38.112    1234  100124       0
3   FAD0839C1A95 2020-07-27 00:05:38.000    1234  100123       2
4   FAD0839C1A95 2020-07-27 00:06:39.000    1234  100123       1
5   A2750A7B6C24 2020-07-27 00:16:50.592    4321  100123       0
6   03F5DF150A3C 2020-07-27 00:17:00.246    4321  100124       0
7   03F5DF150A3C 2020-07-27 00:18:00.000    4321  100124       1
8   03F5DF150A3C 2020-07-27 00:20:00.000    4321  100124       2
9   03F5DF150A3C 2020-07-27 00:22:00.000    4321  100124       3
10  03F5DF150A3C 2020-07-27 00:23:00.000    4321  100124       3
11  03F5DF150BBB 2020-07-27 00:23:00.000    4321  100124       3

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-