简体   繁体   English

numpy数组如何使用for循环?

[英]how to use for loop with numpy array?

i have a part of code like this 我有一部分这样的代码

#predicitng values one by one 
regr = linear_model.LinearRegression()
predicted_value = np.array([ 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32])
predicted_value =  predicted_value.reshape(-1,1)


#mt
regr.fit(x, y)
predicted_values = regr.predict(predicted_value)
predict_outcome = regr.predict(predicted_value)
predictions = {'predicted_value': predict_outcome}
mmt = np.mean(predict_outcome)

#ht
regr.fit(x, ht)
predicted_values = regr.predict(predicted_value)
predict_outcome = regr.predict(predicted_value)
predictions = {'predicted_value': predict_outcome}
mht = np.mean(predict_outcome)

here instead of this : 这里代替这个:

predicted_value = np.array([ 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32])

how can i set a range from 9 to 32(or x to y) so that i can avoid typing all numbers.if it is done using for loop how to apply it in this context 我如何设置从9到32(或x到y)的范围,这样我就可以避免键入所有数字。如果使用for循环完成了该如何在此上下文中应用它

There is no need to use a loop. 无需使用循环。 You can use numpy.arange([start, ]stop, [step, ]) to generate a range of numbers. 您可以使用numpy.arange([start, ]stop, [step, ])生成一定范围的数字。

In your case: 在您的情况下:

predicted_value = np.arange(9, 33)  # Note the 33 if you want 9..32

If you really want to use a loop, there is the option of using a list comprehension : 如果您确实想使用循环,则可以选择使用列表推导

predicted_value = np.array([i for i in range(9, 33)])

Or an explicit loop, which would be most horrible: 或一个显式循环,这将是最可怕的:

predicted_value = np.empty(33 - 9)
for k, i in enumerate(range(9, 33)):
    predicted_value[k] = i
predicted_value = np.array([i for i in range(9, 33)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM