我的数据如下所示

name     first_appear      last_appear
Bob      12:10:00          12:33:49
Jacob    12:31:00          13:29:12

我怎么才能按时间范围分组并像这样计算呢

  Interval        Count
10:00 - 11:00       0
11:00 - 12:00       0
12:00 - 13:00       2
13:00 - 14:00       1
14:00 - 15:00       0

Explanation:

Bob从12:1012:33,所以在12:00 - 13:00上加1

雅各从12:3113:29,所以在12:00 - 13:0013:00 - 14:00之间加1


我使用的是Python3.9,输入是Pandas DataFrame,但如果需要,可以进行重构 first_appearlast_appeardatetime.time个对象

谢谢

推荐答案

好的,我可能有一个解决方案,这是一个小暴力,因为我不知道你问题的限制,我也没有一个最小可重现的例子,我使用了嵌套的for循环(我知道),但在这里可能使用Pandas 的dataframe.Apply方法.不管怎么说:

您的框架:

import pandas as pd
from datetime import datetime, time

Data = pd.DataFrame(
{
 "name":["Bob", "Jacob"],
 "first_appear":[datetime.strptime("12:10:00", '%H:%M:%S').time(), datetime.strptime('12:31:00', '%H:%M:%S').time()],
 "last_appear":[datetime.strptime('12:33:49', '%H:%M:%S').time(), datetime.strptime('13:29:12', '%H:%M:%S').time()]
 }
)

#Assuming you want the names as the index, and not as a column 
Data = Data.set_index("name", drop=True)

IntFrame = pd.DataFrame(
    {"Interval":[time(i) for i in range(10, 16)],
     "Count":0}
    )

和嵌套循环:

for index1, index2 in zip(IntFrame.index.values[:-1], IntFrame.index.values[1:]):
for i in Data.index.values:
    First = Data.loc[i, "first_appear"]
    Last = Data.loc[i, "last_appear"]
    if (First >= IntFrame.loc[index1, "Interval"] and First < IntFrame.loc[index2, "Interval"]):
        IntFrame.loc[index1, "Count"] += 1
        if Last >= IntFrame.loc[index2, "Interval"]:
            #gets the last position where 'Last' is greater than a time interval
            Index3 = max(IntFrame.where(Last >= IntFrame["Interval"]).dropna().index.values)
            IntFrame.loc[index2:Index3, "Count"] += 1

这将产生:

   Interval  Count
0  10:00:00      0
1  11:00:00      0
2  12:00:00      2
3  13:00:00      1
4  14:00:00      0
5  15:00:00      0

我劝你不要把你的时间间隔当作一个二元组,因为它隐含在一个时间尺度上.在处理数据帧时,这样做是不好的.

Python相关问答推荐

如何创建一个缓冲区周围的一行与manim?

python中字符串的条件替换

当递归函数的返回值未绑定到变量时,非局部变量不更新:

用渐近模计算含符号的矩阵乘法

通过ManyToMany字段与Through在Django Admin中过滤

未调用自定义JSON编码器

python中csv. Dictreader. fieldname的类型是什么?'

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

Pandas—堆栈多索引头,但不包括第一列

如何在一组行中找到循环?

极点替换值大于组内另一个极点数据帧的最大值

Scipy差分进化:如何传递矩阵作为参数进行优化?

操作布尔值的Series时出现索引问题

如何在Python中从html页面中提取html链接?

随机森林n_估计器的计算

是否将Pandas 数据帧标题/标题以纯文本格式转换为字符串输出?

#将多条一维曲线计算成其二维数组(图像)表示

有没有一种方法可以根据不同索引集的数组从2D数组的对称子矩阵高效地构造3D数组?

判断字典中是否有多个值对

在Python Polar中从一个函数调用添加多个列