gpt4 book ai didi

python - 有没有办法在 python 中将 bincount 与子句一起使用?

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:31 24 4
gpt4 key购买 nike

我有关于自行车租赁需求和天气的每小时数据。我想根据好天气和坏天气分别绘制每小时的平均需求量。

当我绘制给定小时的平均需求(不考虑天气)时,我所做的是计算给定小时的租赁总需求,然后除以总小时数:

hour_count = np.bincount(hour)
for i in range(number_of_observations):
hour_sums[hour[i]] = hour_sums[hour[i]] + rentals[i]

av_rentals = [x/y for x,y in zip(hour_sums,hour_count)]

现在我想做同样的事情,但分别针对好天气和坏天气。累加和很简单,我只是添加了一个“if”子句。我不知道如何计算好天气和坏天气的时间。我宁愿避免像总和那样做一个大循环......任何与 bincount 相同但带有子句的函数?像这样的东西:

good_weather_hour_count = np.bincount(hour, weather == 1 or weather == 2)

有什么想法吗?
附言。也许有人知道如何在没有循环的情况下计算给定小时内的租金?我尝试了一些带有 2d 直方图的东西,但它没有用。

label_sums = np.histogram2d(hour, rentals, bins=24)[0]

最佳答案

np.bincount has a weights parameter您可以使用它来计算小时数按租赁数量加权。例如,

In [39]: np.bincount([1,2,3,1], weights=[20,10,40,10])
Out[39]: array([ 0., 30., 10., 40.])

因此,您可以替换 for 循环:

for i in range(number_of_observations):
hour_sums[hour[i]] = hour_sums[hour[i]] + rentals[i]

hour_sums = np.bincount(hour, weights=rentals, minlength=24) 

要处理好/坏天气,您可以屏蔽小时租金数据以仅选择适用的数据子集:

mask = (weather == w)
masked_hour = hour[mask]
masked_rentals = rentals[mask]

然后计算masked_hourmasked_rentals:

import numpy as np

np.random.seed(2016)
N = 2
hour = np.tile(np.arange(24), N)
rentals = np.random.randint(10, size=(len(hour),))
# say, weather=1 means good weather, 2 means bad weather
weather = np.random.randint(1, 3, size=(len(hour),))

average_rentals = dict()
for kind, w in zip(['good', 'bad', 'all'], [1, 2, None]):
if w is None:
mask = slice(None)
else:
mask = (weather == w)
masked_hour = hour[mask]
masked_rentals = rentals[mask]
total_rentals = np.bincount(masked_hour, weights=masked_rentals, minlength=24)
total_hours = np.bincount(masked_hour, minlength=24)
average_rentals[kind] = (total_rentals / total_hours)

for kind, result in average_rentals.items():
print('\n{}: {}'.format(kind, result))

产量

bad: [ 4.   6.   2.   5.5  nan  4.   4.   8.   nan  3.   nan  2.5  4.   nan  9.
nan 3. 5.5 8. nan 8. 5. 9. 4. ]

good: [ 3. nan 4. nan 8. 4. nan 7. 5.5 2. 4. nan nan 0.5 9.
0.5 nan nan 5. 7. 1. 7. 8. 0. ]

all: [ 3.5 6. 3. 5.5 8. 4. 4. 7.5 5.5 2.5 4. 2.5 4. 0.5 9.
0.5 3. 5.5 6.5 7. 4.5 6. 8.5 2. ]

关于python - 有没有办法在 python 中将 bincount 与子句一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36554788/

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