numpy数组的numpy数组 [英] Numpy array of numpy arrays
本文介绍了numpy数组的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我创建一个由等长子列表组成的 numy 数组时,它隐式地将其转换为 (len(list), len(sub_list))
二维数组:
但是当我传递可变长度的子列表时,它会创建一个长度为 len(list)
的向量:
当子列表的长度相同时,如何获得向量输出(即使第一种情况表现得像第二种情况)?
解决方案
给你...创建dtype=np.ndarray
而不是dtype=object
.
下面的简单示例(有 5 个元素):
在[1]中:arr = np.empty((5,), dtype=np.ndarray)在 [2]: arr.shape输出[2]:(5,)在 [3] 中:arr[0]=np.array([1,2])在 [4] 中:arr[1]=np.array([2,3])在 [5] 中:arr[2]=np.array([1,2,3,4])在 [6]: arr出[6]:数组([数组([1, 2]), 数组([2, 3]), 数组([1, 2, 3, 4]), 无, 无],数据类型=对象)
When I create a numy array of a list of sublists of equal length, it implicitly converts it to a (len(list), len(sub_list))
2d array:
>>> np.array([[1,2], [1,2]],dtype=object).shape
(2, 2)
But when I pass variable length sublists it creates a vector of length len(list)
:
>>> np.array([[1,2], [1,2,3]],dtype=object).shape
(2,)
How can I get a vector output when the sublists are the same length (i.e. make the first case behave like the second)?
解决方案
Here you go...create with dtype=np.ndarray
instead of dtype=object
.
Simple example below (with 5 elements):
In [1]: arr = np.empty((5,), dtype=np.ndarray)
In [2]: arr.shape
Out[2]: (5,)
In [3]: arr[0]=np.array([1,2])
In [4]: arr[1]=np.array([2,3])
In [5]: arr[2]=np.array([1,2,3,4])
In [6]: arr
Out[6]:
array([array([1, 2]), array([2, 3]), array([1, 2, 3, 4]), None, None],
dtype=object)
这篇关于numpy数组的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文