我列出了人们进入房间并离开房间的日期:
05/04/2017 14:20 05/04/2017 17:54
05/04/2017 13:10 06/04/2017 07:56
05/04/2017 10:30 05/04/2017 11:04
所以一个人在14:20进入并在17:54离开。一个人在一天13:10进入,然后在下一个07:56离开。
我想要做的是查看一天中某些时段之间有多少人在房间里,例如14:00到15:00之间,房间里有两个人。然后我想要绘制这些数据的图表,这样我就可以看到房间里不同时段的人数。
我的问题是,这种分析是否有一个名称,这是像Pandas这样的包可以做的事情。我可以编写一个算法来执行此操作(可能)但在此之前我想检查它是否是一个已知的问题'。
答案 0 :(得分:2)
此类问题出现在不同的应用程序中(例如在物理学中称为mass balance),但AFAIK没有通用名称。但它们的本质是简单计数,因此编写算法比找到完全解决问题的解决方案更容易:)
此代码计算在指定时间内进入或退出房间的人数,然后从第二个中减去第一个:
import pandas as pd
data = pd.DataFrame({'in':[10, 11, 11, 12, 14], 'out':[11, 13, 15, 14, 15]})
count_in = data.groupby('in')['in'].count()
count_out = data.groupby('out')['out'].count()
count_data = pd.concat([count_in, count_out], axis=1).fillna(0).cumsum()
print(count_data['in'] - count_data['out'])
代码给出了结果:
10 1.0
11 2.0
12 3.0
13 2.0
14 2.0
15 0.0
这意味着10岁时有一个人(刚来的人),11岁时有两个人(另外2个人,但1人退出),等等。
答案 1 :(得分:0)
假设您有一个包含日期列表的CSV文件,例如
05/04/2017 14:20,05/04/2017 17:54
05/04/2017 13:10,06/04/2017 07:56
05/04/2017 10:30,05/04/2017 11:04
读取每一行并将每个条目转换为Python datetime
对象。接下来使用Counter()
按小时记录每个条目和退出。日期时间用作删除分钟的字典键。最后迭代可用的小时范围并添加每小时看到的任何条目或出口:
from collections import Counter
from datetime import datetime, timedelta
import csv
in_out = Counter()
one_hour = timedelta(hours=1)
with open('in_out.csv', 'r', newline='') as f_inout:
for row in csv.reader(f_inout):
in_at = datetime.strptime(row[0], "%d/%m/%Y %H:%M").replace(minute=0)
out_at = datetime.strptime(row[1], "%d/%m/%Y %H:%M").replace(minute=0)
in_out[in_at] += 1
in_out[out_at] -= 1
hours = []
room_total = 0
hours_range = sorted(in_out.keys()) # Use to determine start and end hours
hour = hours_range[0]
while hour <= hours_range[-1]:
room_total += in_out.get(hour, 0)
hours.append((hour, room_total))
hour += one_hour
for hour, room_total in hours:
print(hour, room_total)
这给出了以下每小时细分:
2017-04-05 10:00:00 1
2017-04-05 11:00:00 0
2017-04-05 12:00:00 0
2017-04-05 13:00:00 1
2017-04-05 14:00:00 2
2017-04-05 15:00:00 2
2017-04-05 16:00:00 2
2017-04-05 17:00:00 1
2017-04-05 18:00:00 1
2017-04-05 19:00:00 1
2017-04-05 20:00:00 1
2017-04-05 21:00:00 1
2017-04-05 22:00:00 1
2017-04-05 23:00:00 1
2017-04-06 00:00:00 1
2017-04-06 01:00:00 1
2017-04-06 02:00:00 1
2017-04-06 03:00:00 1
2017-04-06 04:00:00 1
2017-04-06 05:00:00 1
2017-04-06 06:00:00 1
2017-04-06 07:00:00 0