【问题标题】:Can't assign the "sum of np.random.normal" in a element of array无法在数组元素中分配“np.random.normal 之和”
【发布时间】:2023-01-02 00:29:40
【问题描述】:

我正在尝试通过 random.normal 生成随机数并获取它们的摘要。然后,我尝试将值分配给数组sum 中的每个元素。 我通过 np.zeros 创建了一个零数组(浮点型),然后按以下方式分配值。
我试图利用 numpy 和 matlibplot.pyplot 作为库来执行此操作。
我的代码:

np.random.seed(0)
sum=np.zeros(10,dtype=float)
for i in np.arange(1,11):
    X = np.random.normal(size=(10,1))
    Y=np.sum(X,axis=1)
    sum[i-1]=Y
print(sum)

当我在 Google Colab 上执行此代码时,发生了以下错误。

TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-14-33fba8ac5d90> in <module>
      6     X = np.random.normal(size=(10,1))
      7     Y=np.sum(X,axis=1)
----> 8     sum[i-1]=Y
      9 print(sum)

ValueError: setting an array element with a sequence.

你能告诉我如何解决这个错误吗?

【问题讨论】:

    标签: python numpy-random


    【解决方案1】:

    您创建的 X 数组的大小为 10 x 1。当您执行 numpy sum 时,您选择的轴是基于 0 的,因此您正在对“1”维度(第二维度)和为 Y 获取仍然是 10 x 1 的数组。

    要修复它,您需要将轴设置为 0

    X = np.random.normal(size=(10,1))
    Y = np.sum(X,axis=0)
    

    或者完全省略轴参数以返回标量而不是大小为 1 的数组

    X = np.random.normal(size=(10,1))
    Y = np.sum(X)
    

    作为旁注,不建议使用 sum 作为变量名,因为这是内置 python 方法的名称,如果您稍后尝试使用内置的求和函数,可能会导致错误——但这不是问题的根源在这里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2021-06-30
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      相关资源
      最近更新 更多