Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 忽略numpy'中的嵌套结构;s数组创建_Python_Arrays_List_Numpy - Fatal编程技术网

Python 忽略numpy'中的嵌套结构;s数组创建

Python 忽略numpy'中的嵌套结构;s数组创建,python,arrays,list,numpy,Python,Arrays,List,Numpy,我想写入一个vlen hdf5数据集,为此我使用h5py.dataset.write_direct来加速这个过程。假设我有一个numpy数组列表(例如,由cv2.findContours)和数据集给出: dataset = h5file.create_dataset('dataset', \ shape=..., \ dtype=h5py.special_type(vl

我想写入一个vlen hdf5数据集,为此我使用
h5py.dataset.write_direct
来加速这个过程。假设我有一个numpy数组列表(例如,由
cv2.findContours
)和数据集给出:

dataset = h5file.create_dataset('dataset', \
                                shape=..., \
                                dtype=h5py.special_type(vlen='int32'))
contours = [numpy array, ...]
要将
等高线
写入切片
dest
给定的目的地,我必须首先将
等高线
转换为numpy数组的numpy数组:

contours = numpy.array(contours) # shape=(len(contours),); dtype=object
dataset.write_direct(contours, None, dest)
但这仅适用于轮廓中的所有numpy阵列具有不同形状的情况,例如:

contours = [np.zeros((10,), 'int32'), np.zeros((10,), 'int32')]
contours = numpy.array(contours) # shape=(2,10); dtype='int32'
问题是:如何让numpy创建对象数组


可能的解决办法:

手动创建:

contours_np = np.empty((len(contours),), dtype=object)
for i, contour in enumerate(contours):
    contours_np[i] = contour
但是循环速度非常慢,因此使用
map

map(lambda (i, contour): contour.__setitem_(i, contour),  \
    enumerate(contours))
我测试了第二个选项,速度是上述选项的两倍,但也非常难看:

contours = np.array(contours + [None])[:-1]
以下是微观基准:

l = [np.random.normal(size=100) for _ in range(1000)]
备选案文1:

$ start = time.time(); l_array = np.zeros(shape=(len(l),), dtype='O'); map(lambda (i, c): l_array.__setitem__(i, c), enumerate(l)); end = time.time(); print("%fms" % ((end - start) * 10**3))
0.950098ms
备选案文2:

$ start = time.time(); np.array(l + [None])[:-1]; end = time.time(); print("%fms" % ((end - start) * 10**3))
0.409842ms

这看起来有点难看,还有其他建议吗?

一个解决方案似乎是先创建“外部”数组(使用“对象”数据类型),然后用内部数组填充元素

因此:

导致

[array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)
 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)]

array([array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32),
       array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)], dtype=object)
在这个版本中

contours_np = np.empty((len(contours),), dtype=object)
for i, contour in enumerate(contours):
    contours_np[i] = contour
可以用单个语句替换循环

contours_np[...] = contours

这就是我一直在寻找的:)
contours_np[...] = contours