【问题标题】:Merge numpy arrays returned from loop合并从循环返回的numpy数组
【发布时间】:2014-03-26 13:49:03
【问题描述】:

我有一个生成 numpy 数组的循环:

for x in range(0, 1000):
   myArray = myFunction(x)

返回的数组总是一维的。我想将所有数组组合成一个数组(也是一维的。

我尝试了以下方法,但失败了

allArrays = []
for x in range(0, 1000):
   myArray = myFunction(x)
   allArrays += myArray

错误是ValueError: operands could not be broadcast together with shapes (0) (9095)。我怎样才能让它工作?

例如这两个数组:

[ 234 342 234 5454 34 6]
[ 23 2 1 4 55 34]

应合并到这个数组中:

[ 234 342 234 5454 34 6 23 2 1 4 55 34 ]

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

你可能是说

allArrays = np.array([])
for x in range(0, 1000):
    myArray = myFunction(x)
    allArrays = np.concatenate([allArrays, myArray])

更简洁的方法(见 wims 答案)是使用list comprehension

allArrays = np.concatenate([myFunction(x) for x in range]) 

【讨论】:

  • 如果我使用你的第一个例子。我收到错误TypeError: only length-1 arrays can be converted to Python scalars
  • @ustroetz:感谢您的关注,忘记了括号,因为 concatenate 将数组连接为一个列表。
  • 它不起作用,它说all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 3 dimension(s)
  • 如果你检查OP,这个问题和答案是针对一维输出数组的情况。从您的评论中可以清楚地看出,您拥有的输出数组并不总是一维的(请注意错误消息如何引用 3 维数组)。
【解决方案2】:
allArrays = np.concatenate([myFunction(x) for x in range(1000)])

【讨论】:

    【解决方案3】:

    你应该知道返回数组的形状。假设,myArray.shape = (2, 4) 那么

    allArrays = np.empty((0, 4))
    for x in range(0, 1000):
        myArray = myFunction(x)
        allArrays = np.append(allArrays, myArray, axis = 0)
    

    【讨论】:

    • 这不是将第一行作为空值吗?
    • 不,因为我们创建了 0 行 4 列的数组:array([], shape=(0, 4), dtype=float64)
    猜你喜欢
    • 1970-01-01
    • 2013-03-11
    • 2018-01-14
    • 1970-01-01
    • 2011-09-23
    • 2018-07-25
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多