如何制作具有不同行大小的多维numpy数组? [英] How to make a multidimension numpy array with a varying row size?
问题描述
我想创建一个二维 numpy 数组,每行具有不同数量的元素.
I would like to create a two dimensional numpy array of arrays that has a different number of elements on each row.
尝试
cells = numpy.array([[0,1,2,3], [2,3,4]])
报错
ValueError: setting an array element with a sequence.
推荐答案
虽然 Numpy 知道任意对象的数组,但它针对具有固定维度的同构数字数组进行了优化.如果您确实需要数组数组,最好使用嵌套列表.但是根据数据的预期用途,不同的数据结构可能会更好,例如如果您有一些无效的数据点,则使用屏蔽数组.
While Numpy knows about arrays of arbitrary objects, it's optimized for homogeneous arrays of numbers with fixed dimensions. If you really need arrays of arrays, better use a nested list. But depending on the intended use of your data, different data structures might be even better, e.g. a masked array if you have some invalid data points.
如果您真的想要灵活的 Numpy 数组,请使用以下内容:
If you really want flexible Numpy arrays, use something like this:
numpy.array([[0,1,2,3], [2,3,4]], dtype=object)
然而,这将创建一个存储对列表的引用的一维数组,这意味着您将失去 Numpy 的大部分优势(向量处理、局部性、切片等).
However this will create a one-dimensional array that stores references to lists, which means that you will lose most of the benefits of Numpy (vector processing, locality, slicing, etc.).
这篇关于如何制作具有不同行大小的多维numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!