我使用大熊猫数据框,寄存器的日期和时间以及放电的日期和时间写为'2013-01-01 01:41:01'。
创建此人群(小时)数据的最简单,最优雅的方法是什么? 我本来只是想编写一个非常特定的for循环和一个count函数,但是在开始进行此类探索之前,我很乐意考虑您的见解(:!
在很多情况下,出院日期和时间为NAN,这是因为这些病例并未出院,而是转移到医院的某个部门。
示例
让我说我有这个数据集
case RegisterDateTime DischargeDateTime. TransferDateTime
0 '2013-01-01 00:12:00' '2013-01-01 00:48:00' NAN
1 '2013-01-01 00:43:00' '2013-01-01 02:12:00' NAN
2 '2013-01-01 00:56:00' '2013-01-01 01:22:00' NAN
3 '2013-01-01 01:04:00' '2013-01-01 04:12:00' NAN
4 '2013-01-01 01:34:00' '2013-01-01 04:52:00' NAN
5 '2013-01-01 02:01:00' NAN '2013-01-01 05:34:00'
所以我想拥有一个“人群”数据集,它可以每天和每小时告诉我目前的人数。 在这个例子中,我们可以看到 人群('2013-01-01',0)= 2(为什么?因为没有预先登记的案件,案件0,1,2在第0小时被登记,案件0出院-> 0 + 3-1 = 2) 人群('2013-01-01',1)= 3(为什么?案例1,2已预先注册,案例3,4在第一小时内已注册,案例2已出院-> 2 + 2-1 = 3) 我希望这个主意现在明白了。
另外,关于排放和转移,它们是相辅相成的,所以我只需要弄清楚如何将它们合并为一列并擦除NANs
答案 0 :(得分:1)
这是一种方法。很像您在帖子中描述的想法,但这是一个漫长的步骤。也许,其他人的实现可能更短。
import pandas as pd
>>>df
case RegisterDateTime DischargeDateTime TransferDateTime
0 0 1/1/13 0:12 1/1/13 0:48 NaN
1 1 1/1/13 0:43 1/1/13 2:12 NaN
2 2 1/1/13 0:56 1/1/13 1:22 NaN
3 3 1/1/13 1:04 1/1/13 4:12 NaN
4 4 1/1/13 1:34 1/1/13 4:52 NaN
5 5 1/1/13 2:01 NaN 1/1/13 5:34
# Construct population outflow. This is where you merge Discharges with Transfers
df_out = pd.DataFrame([(j,k) if str(k) != 'nan' else (j,v) for j, k, v in zip(df['case'], df['DischargeDateTime'],df['TransferDateTime'])])
df_out.columns = ['out', 'time']
# You can skip this if your column is already in DateTime
df_out['time'] = pd.to_datetime(df_out['time'])
# Needed for resampling
df_out.set_index('time', inplace=True)
df_out = df_out.resample('H').count().cumsum()
# Needed for merging later
df_out.reset_index(inplace=True)
>>>df_out
out
time
2013-01-01 00:00:00 1
2013-01-01 01:00:00 2
2013-01-01 02:00:00 3
2013-01-01 03:00:00 3
2013-01-01 04:00:00 5
2013-01-01 05:00:00 6
# Now, repeat for the population inflow
df_in = df.loc[:, ['case', 'RegisterDateTime']]
df_in.columns = ['in', 'time']
df_in['time'] = pd.to_datetime(df_in['time'])
df_in.set_index('time', inplace=True)
df_in = df_in.resample('H').count().cumsum()
df_in.reset_index(inplace=True)
>>>df_in
in
time
2013-01-01 00:00:00 3
2013-01-01 01:00:00 5
2013-01-01 02:00:00 6
# You can now combine the two
df= pd.merge(df_in, df_out)
df['population'] = df['in'] - df['out']
>>>df
time in out population
0 2013-01-01 00:00:00 3 1 2
1 2013-01-01 01:00:00 5 2 3
2 2013-01-01 02:00:00 6 3 3