【问题标题】:Numpy cannot broadcast arrayNumpy 无法广播数组
【发布时间】:2016-01-29 13:51:39
【问题描述】:

我正在编写代码来模仿康威的生命游戏(10 细胞系)。我快完成了,但我的代码给了我错误

could not broadcast array from shape (7,11) into shape (10)

这是我认为问题所在的代码。

glider = np.zeros([7,11])
glider[3,:]=1
glider[(3,0)]=0
glider[(3,10)]=0
N=(10) # the domain is NxN, N=10 for testing, more interesting with N=100
init_choice = 1 # 0 for random initialization
c = np.random.choice( (1,0), N*N, p=[0.3,0.7] ).reshape(N,N) # default initialization is random
if init_choice == 1:
    c = c*0
    c[3,:] = glider # put glider in top left
if init_choice == 2:
    print("not implemented yet")

periodic(c)

给出结果

-----------------------------------------------------------------------------------
ValueError                                        Traceback (most recent call last)
<ipython-input-53-0a8812bfb2f8> in <module>()
      4 if init_choice == 1:
      5     c = c*0
      6     c[3,:] = glider # put glider in top left
      7 if init_choice == 2:
      8     print("not implemented yet")

ValueError: could not broadcast input array from shape (7,11) into shape (10)

这是screenshot

【问题讨论】:

    标签: arrays python-3.x numpy anaconda


    【解决方案1】:

    cglider 的形状不匹配。以交互方式尝试。一个是 10x10,另一个是 7x11。

    在一维中将一个数组复制到另一个(更大的)数组涉及到:

    A = np.zeros(10)
    B = np.ones(2)
    A[3:5] = B
    

    【讨论】:

    • 我想我不知道在哪里改变c的大小
    • 这是一个基本的 numpy 索引问题,您需要自己解决。如何将任何形状的滑翔机放在c 中相同形状的单元格子集中。从小处着手 - 1 个单元、2 个、2x2 等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2017-06-18
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多