Python 如何在1D Numpy浮点数组上获取for循环中的项的实际值?
我必须使用for循环为numpy浮点数组中的随机数添加平方和,但是我无法得到最终的和,而只能得到一个数组。我从浮点数组的循环中得到的项的类型似乎是1d数组项,而不是实际值 当我创建一个随机整数数组时,循环的和就起作用了。这是在jupyter笔记本中运行的。我希望原始总和看起来像sum2。谢谢Python 如何在1D Numpy浮点数组上获取for循环中的项的实际值?,python,arrays,numpy,Python,Arrays,Numpy,我必须使用for循环为numpy浮点数组中的随机数添加平方和,但是我无法得到最终的和,而只能得到一个数组。我从浮点数组的循环中得到的项的类型似乎是1d数组项,而不是实际值 当我创建一个随机整数数组时,循环的和就起作用了。这是在jupyter笔记本中运行的。我希望原始总和看起来像sum2。谢谢 test = np.random.randn(1,5000000) sum = float(0) test2 = np.random.randint(1,11,5000000) sum2 = float(0
test = np.random.randn(1,5000000)
sum = float(0)
test2 = np.random.randint(1,11,5000000)
sum2 = float(0)
test
for x in test:
sum = sum + (x * x)
print(sum)
输出:[0.90913299 1.41379817 0.62241195…6.05354146 0.37052478 0.60846973]
test2
for x in test2:
sum2 = sum2 + (x * x)
print(sum2)
输出:192468061.0
测试
是一个2d数组:
In [16]: test = np.random.randn(1,10)
In [17]: test.shape
Out[17]: (1, 10)
In [18]: test
Out[18]:
array([[-0.24668889, 1.63924792, 0.43071196, -0.48847854, 1.68450449,
-0.32010578, -0.62775688, -1.15134612, 2.42900228, 1.16697956]])
此迭代操作第一个维度,即大小1:
In [20]: for x in test:
...: print(x)
[-0.24668889 1.63924792 0.43071196 -0.48847854 1.68450449 -0.32010578
-0.62775688 -1.15134612 2.42900228 1.16697956]
在您的代码中,for的每次只将一行输入到您的总和中
test2
是一个1d阵列:
In [21]: test2 = np.random.randint(1,11,10)
In [22]: test2.shape
Out[22]: (10,)
In [23]: test2
Out[23]: array([ 3, 8, 3, 1, 1, 3, 10, 6, 6, 10])
In [24]: for x in test2:
...: print(x)
...:
3
8
3
1
1
3
10
6
6
10
我不知道为什么,但是如果您使用len(test)
和len(test2)
检查test
和test2的大小,您会注意到差异
要获得与sum2
类似的结果,可以运行:
sum=0
对于测试[0]中的x:
总和+=x*x
为什么要为此使用循环?它违背了使用Numpy的目的。不管怎样,如果你看到randn()
给你一个不同的形状,它的使用不鼓励使用standard\u normal
。感谢你的直觉。我需要将手动for循环迭代与更好的使用Numpy的方法进行比较@Markmeyer您可以执行类似于np.sum(test**2)
的操作,它将比python循环快几个数量级。