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

查看:49
本文介绍了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 数组:这是 NumPy 与基本 Python 相比非常不擅长的一种操作.这是因为您每次 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天全站免登陆