gpt4 book ai didi

remove loops with numpy(使用NumPy删除循环)

转载 作者:bug小助手 更新时间:2023-10-25 19:31:05 28 4
gpt4 key购买 nike



def demand_y(self, prices):
markt_prices = prices.copy()
y = [0]*len(prices)
for mp in range(len(markt_prices)):
for p in prices:
if(p >= markt_prices[mp]):
y[mp] +=1
return y

I'm trying to plot a demand and supply chart and this function returns me the y data points (how many people are willing to buy for a specific price).

我正在尝试绘制一个需求和供应图表,这个函数向我返回y个数据点(有多少人愿意以特定价格购买)。


The functions works but I am sure there is a way to get it done more efficient with numpy.

这些函数可以工作,但我相信有一种方法可以用NumPy更高效地完成它。


更多回答

You can accept an answer by clicking the check next to one of the answers.

您可以通过单击其中一个答案旁边的复选标记来接受答案。

优秀答案推荐

IIUC, you can do:

IIUC,您可以:


prices = np.array([10, 20, 30, 10, 20, 50])
print((prices[:, None] <= prices[None, :]).sum(axis=1))

Prints:

打印:


[6 4 2 6 4 1]


Broadcast comparison and sum by column:

广播比较和按列求和:


>>> prices = np.random.rand(10)
>>> prices
array([0.5875545 , 0.25082088, 0.60516259, 0.74796803, 0.20443016,
0.46121859, 0.52371397, 0.31880511, 0.26756963, 0.75844983])

>>> np.greater_equal.outer(prices, prices).sum(0)
array([ 4, 9, 3, 2, 10, 6, 5, 7, 8, 1])

>>> (prices[:, None] >= prices).sum(0)
array([ 4, 9, 3, 2, 10, 6, 5, 7, 8, 1])

更多回答

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