正在创建一个列表,该列表的值计数取决于具有时间戳的另一列中的时间间隔



假设我有一个pandas数据帧,它有两列,一个字符串和一个日期时间,如下所示:

ORDER        TIMESTAMP
GO     6/4/2019 09:59:49.497000
STAY   6/4/2019 09:05:27.036000
WAIT   6/4/2019 10:33:05.645000
GO     6/4/2019 10:28:03.649000
STAY   6/4/2019 11:23:11.614000
GO     6/4/2019 11:00:33.574000
WAIT   6/4/2019 11:41:55.744000

我想创建一个列表,其中每个条目都是一个包含三个值的列表。对于所选的每个时间间隔(比如一个小时(,每个条目都是:[开始时间、总行数、按GO顺序排列的行的百分比]。

例如,对于上面的数据帧,我的列表是:

[6/4/2019 09:00:00.000000, 2, 50]
[6/4/2019 10:00:00.000000, 2, 50]
[6/4/2019 11:00:00.000000, 3, 33.3]

我创建了一个简单的while循环:

go= []
while t<=df["timestamp"].iloc[-1]:
tmp1 = df[(df["date_time"]>=t) & (df["timestamp"]<t+timedelta(hour=1))]
tmp2 = df[(df["date_time"]>=t) & (df["timestamp"]<t+timedelta(hour=1)) & (df["Order"]=="GO")]
go.append([t, tmp1.shape[0], 100.0*tmp2.shape[0]/tmp1.shape[0]])
#increment the time by the interval
t=t+timedelta(hour=1)

然而,我的初始数据帧有数百万行,我希望我的时间间隔比一个小时短得多,所以这种方法非常慢。更像蟒蛇的方式是什么?

让我们用groupby().agg()size来计算行数,用mean来获得GO:的行数比

(df.ORDER.eq('GO').astype(int)
.groupby(df.TIMESTAMP.dt.floor('1H'))   # groupby interval of choice
.agg(['size','mean'])
.reset_index()              # get timestamp back
.to_numpy().tolist()        # this is to generate the list
)

输出:

[[Timestamp('2019-06-04 09:00:00'), 2, 0.5],
[Timestamp('2019-06-04 10:00:00'), 2, 0.5],
[Timestamp('2019-06-04 11:00:00'), 3, 0.3333333333333333]]

最新更新