如何创建一个充满空列表的新numpy数组?

2024-04-19 02:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想生成一个填充了空列表的numpy数组。我试过这个:

import numpy as np

arr=np.full(6, fill_value=[], dtype=object)

我犯了一个错误:

ValueError: could not broadcast input array from shape (0) into shape (6)

但如果我使用:

arr = np.empty(6, dtype=object)
arr.fill([])

没关系。为什么numpy.full在这里不起作用?初始化充满空列表的数组的正确方法是什么


Tags: importnumpy列表objectvalueas错误np
2条回答

您可以尝试使用numpy.empty(shape,dtype=float,order='C')

无法使用fill_value=[]的原因隐藏在文档中:

在文档中,它说^{}fill_value参数是标量或类似数组的。在^{}的文档中,您可以找到它们的数组定义,如:

Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

因此,列表被专门视为“数组”填充类型,而不是标量,这不是您想要的。此外,arr.fill([])实际上并不是您想要的,因为它会将每个元素填充到相同的列表中,这意味着附加到一个元素会附加到所有元素。为了避免这种情况,您可以在this answer状态下执行此操作,只需使用列表初始化数组:

arr = np.empty(6, dtype=object)
arr[...] = [[] for _ in range(arr.shape[0])]

这将创建一个包含6个唯一列表的数组,这样附加到一个列表不会附加到所有列表

相关问题 更多 >