【问题标题】:How to count the number of customers in a system in different timestamp without using "for loops" in Python如何在不使用 Python 中的“for 循环”的情况下计算系统中不同时间戳的客户数量
【发布时间】:2021-12-06 21:07:46
【问题描述】:

我想根据他们的到达和离开日期时间计算每小时系统中的客户数量。我可以使用for 循环计算客户数量。如何在不使用for 循环的情况下对问题进行编码?

这是我的带有for 循环的代码:

 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

输入:

每小时时间戳:

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

输出:

谢谢,

【问题讨论】:

  • 请给我们您的实际代码,而不是您的代码图片。真的很难帮你。
  • 我编辑了我的帖子并添加了实际代码。谢谢

标签: python count


【解决方案1】:

你可以稍微简化一下:

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)))

如果您知道 "Census" 字段最初为 0,则可以将 += 更改为 =

这段代码使用了 True 在算术上表现得像 1 而 False 在算术上表现得像 0 这个事实。

我不知道有什么办法可以摆脱外循环。

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多