简体   繁体   中英

How to count the number of customers in a system in different timestamp without using "for loops" in Python

I want to count the number of customers in a system in every hour based on their arrival and departure datetime. I can count the number of customers using for loops. How can I code the problem without using "for loops"? here is my code with "for loops"?

for i in range(0,len(time_range),1):

 for j in range(0,len(test),1):

    if (time_range.loc[i,'Time']>= test.loc[j,"Arrival"]) and (time_range.loc[i,'Time']<test.loc[j,"Departure"]):

        time_range.loc[i,"Census"]=time_range.loc[i,"Census"]+1

我的代码

Here are my inputs:

每小时时间戳

3位客户的到达和离开时间

here is the output:

在此处输入图像描述

Thank you,

You can simplify slightly:

for i in range(len(test)):
    time_range.loc[i, "Census"] += sum(
        test.loc[j, "Arrival"] <= time_range.loc[i, "Time"] < test.loc[j, "Departure"]
        for j in range(len(test)))

You can change the += to just = if you know the "Census" field is initially 0.

This code uses that fact that True behaves like 1 and False behaves like 0 in arithmetic.

I don't know any way of getting rid of the outer loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM