【发布时间】:2018-06-05 19:37:47
【问题描述】:
我有一个列表列表,其中包含两个值,分别代表开始时间点和结束时间点。我想计算两点之间的时间范围有多少落入垃圾箱。
垃圾箱介于 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
感谢阅读
【问题讨论】:
-
你能解释一下你的代码在这里做什么吗?
标签: pandas numpy time-series bins