gpt4 book ai didi

pandas - python : checking which bins two time points belong to

转载 作者:行者123 更新时间:2023-12-02 07:26:16 25 4
gpt4 key购买 nike

我有一个列表列表,其中有两个值,分别代表开始时间点和结束时间点。我想计算两点之间的时间范围有多少属于垃圾箱。

垃圾箱的范围是 0-300,300-500 和 500-1200。我还想将它们划分为 0-50、50-100、100-150 等。

问题类似于Python: Checking to which bin a value belongs ,但有所不同,因为它涉及一个两点时间范围,可以同时落入不同的容器中。

我在下面的代码中创建了 for 循环,它可以工作。但我想知道是否有更快、更 Python 的方法来计算这个,也许使用 pandas 或 numpy。

import numpy
x = numpy.array([[100, 150],[100, 125],[290, 310],[277, 330],
[300, 400],[480, 510],[500, 600]])

d = {'0-300': [0], '300-500': [0], '500-1200':[0]}
import pandas as pd
df = pd.DataFrame(data=d)

for i in x:
start,end = i[0],i[1]

if start <= 300 and end <= 300: # checks if time ranges falls into only 1st bin
df['0-300'][0] += end - start

elif start <= 300 and end > 300: # checks if time ranges falls into 1st and 2ed bin
df['0-300'][0] += (300 - start)
df['300-500'][0] += (end - 300)

elif start >= 300 and end >= 300 and end <= 500: # checks if time ranges falls into only 2ed bin
df['300-500'][0] += end - start

elif start <= 500 and end > 500: # checks if time ranges falls into 2ed and 3ed bin
df['300-500'][0] += (500 - start)
df['500-1200'][0] += (end - 500)

elif start > 500: # checks if time ranges falls into only 3ed bin
df['500-1200'][0] += end - start

df:
0-300 300-500 500-1200
108 160 110

感谢您的阅读

最佳答案

对于一般数量的 bin,这里有一种矢量化方法,利用 np.add.at 获取计数,然后获取 np.add.reduceat 用于获取分箱求和 -

bins = [0, 300, 500, 1200] # Declare bins
id_arr = np.zeros(bins[-1], dtype=int)
np.add.at(id_arr, x[:,0], 1)
np.add.at(id_arr, x[:,1], -1)
c = id_arr.cumsum()
out = np.add.reduceat(c, bins[:-1])

# Present in a dataframe format
col_names = [str(i)+'-' + str(j) for i,j in zip(bins[:-1], bins[1:])]
df_out = pd.DataFrame([out], columns=col_names)

示例输出 -

In [524]: df_out
Out[524]:
0-300 300-500 500-1200
0 108 160 110

关于pandas - python : checking which bins two time points belong to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47953541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com