【问题标题】:Assigning numpy array elements through predefined array通过预定义数组分配numpy数组元素
【发布时间】:2014-04-08 13:48:28
【问题描述】:

我有数组newxnewy,大小分别为nx*nsny*ns,其中nx!=ny
我希望能够通过以下方式在数组f 中设置newxnewy 定义的元素:

f = np.zeros([nx,ny,ns])
for s in range(ns):
    f[newx[:,s],newy[:,s],s] = s

不幸的是,这给出了一个错误:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我理解错误,但我终生无法找出正确的语法。请帮忙。

编辑:提供示例代码:

import numpy as np

newx = np.array([[0,1],
                 [1,2],
                 [2,3],
                 [3,0]])
newy = np.array([[0,1],
                 [1,2],
                 [2,0]])

f = np.zeros([4,3,2])
for s in range(2):
    f[newx[:,s],newy[:,s],s] = s

【问题讨论】:

  • 向我们展示完整的工作代码。
  • newx 和 newy 没有任何意义。如果你想将某个坐标的元素设置为 s,你应该有相同数量的 x,y,s 三元组,而不是不同数量的 x,s 和 y,s 对。

标签: python arrays numpy slice


【解决方案1】:

newx 和 newy 必须具有相同的形状,所以你必须重新塑造它们。

f = np.zeros([4,3,2])

newX = newx.reshape(8,1)
newY = newy.reshape(6,)

for s in range(2):
    f[newX , newY ,s] = s


print f

【讨论】:

  • 好的,你的提示 newx 和 newy 应该是相同的大小是解决方案。谢谢
  • 或者更好:np.tile(np.arange(2),(newx.shape[0],newy.shape[0],1)) 将给出相同的结果。
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2013-11-27
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多