numpy数组的Python numpy数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31250129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:41:15  来源:igfitidea点击:

Python numpy array of numpy arrays

pythonarraysnumpy

提问by Stefano Sandonà

I've got a problem on creating a numpy array of numpy arrays. I would create it in a loop:

我在创建 numpy 数组的 numpy 数组时遇到问题。我会在循环中创建它:

a=np.array([])
while(...):
   ...
   b= //a numpy array generated
   a=np.append(a,b)
   ...

Desired result:

想要的结果:

[[1,5,3], [9,10,1], ..., [4,8,6]]

Real result:

真实结果:

[1,5,3,9,10,1,... 4,8,6]

Is it possible? I don't know the final dimension of the array, so I can't initialize it with a fixed dimension.

是否可以?我不知道数组的最终维度,因此无法使用固定维度对其进行初始化。

采纳答案by nneonneo

Never append to numpyarrays in a loop: it is the one operation that NumPy is very bad at compared with basic Python. This is because you are making a full copy of the data each append, which will cost you quadratic time.

永远不要numpy在循环中附加到数组:与基本 Python 相比,这是 NumPy 非常糟糕的一种操作。这是因为您正在制作每个数据的完整副本append,这将花费您的二次时间。

Instead, just append your arrays to a Python list and convert it at the end; the result is simpler and faster:

相反,只需将您的数组附加到 Python 列表并在最后进行转换;结果更简单、更快:

a = []

while ...:
    b = ... # NumPy array
    a.append(b)
a = np.asarray(a)

As for why your code doesn't work: np.appenddoesn't behave like list.appendat all. In particular, it won't create new dimensions when appending. You would have to create the initial array with two dimensions, then append with an explicit axis argument.

至于为什么你的代码不起作用:np.append根本不像list.append。特别是,它不会在追加时创建新维度。您必须创建具有二维的初始数组,然后附加显式轴参数。

回答by Sunil

we can try it also :

我们也可以试试:

arr1 = np.arange(4)
arr2 = np.arange(5,7)
arr3 = np.arange(7,12)

array_of_arrays = np.array([arr1, arr2, arr3])
array_of_arrays
np.concatenate(array_of_arrays)