numpy数组的Python numpy数组 [英] Python numpy array of numpy arrays

查看:84
本文介绍了numpy数组的Python numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

所需结果:

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

实际结果:

[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.

推荐答案

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

Never append to numpy arrays 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.

相反,只需将数组附加到Python列表中,然后在末尾进行转换;结果更简单,更快捷:

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

a = []

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

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

As for why your code doesn't work: np.append doesn't behave like list.append at 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.

这篇关于numpy数组的Python numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆