【问题标题】:Python declaring a numpy matrix of lists of listsPython声明一个列表列表的numpy矩阵
【发布时间】:2015-06-25 17:39:58
【问题描述】:

我想要一个像这样的 numpy 矩阵 [int, [[int,int]]] 我收到一个类似于“ValueError: setting an array element with a sequence”的错误。

以下是声明

def __init__(self):
    self.path=np.zeros((1, 2))

我尝试在下面的行中为此分配一个值

routes_traveled.path[0, 1]=[loc]

loc 是一个列表,routes_traveled 是对象

【问题讨论】:

标签: python-3.x numpy


【解决方案1】:

你想要一个更高维的数组,比如 3d,还是你真的想要一个元素是 Python lists 的 2d 数组。真正的列表,而不是 numpy 数组?

将列表放入数组的一种方法是使用dtype=object

In [71]: routes=np.zeros((1,2),dtype=object)
In [72]: routes[0,1]=[1,2,3]
In [73]: routes[0,0]=[4,5]

In [74]: routes
Out[74]: array([[[4, 5], [1, 2, 3]]], dtype=object)

这个数组的一个术语是 2 元素列表,另一个是 3 元素列表。

我可以直接创建相同的东西:

In [76]: np.array([[[4,5],[1,2,3]]]) 
Out[76]: array([[[4, 5], [1, 2, 3]]], dtype=object)

但如果我给它 2 个相同长度的列表,我会得到一个 3d 数组:

In [77]: routes1=np.array([[[4,5,6],[1,2,3]]])
Out[77]: 
array([[[4, 5, 6],
        [1, 2, 3]]])

我可以索引最后一个routes1[0,1],并得到一个数组:array([1, 2, 3]),其中routes[0,1] 给出[1, 2, 3]

在这种情况下,您需要清楚在哪里谈论数组、子数组和 Python 列表。


使用dtype=object,元素可以是任何东西——列表、字典、数字、字符串

In [84]: routes[0,0]=3
In [85]: routes
Out[85]: array([[3, [1, 2, 3]]], dtype=object)

请注意,这样的数组失去了纯数字数组所具有的许多功能。数组实际上包含的是指向 Python 对象的指针——只是 Python 列表的一个简单概括。

【讨论】:

  • 您的第一个建议我认为会奏效。我的第一列只是一个 int 而我的第二列是一个对象,这有关系吗?
【解决方案2】:

您想创建一个形状为(1, 2) 的零数组吗?在这种情况下使用np.zeros((1, 2))

In [118]: np.zeros((1, 2))
Out[118]: array([[ 0.,  0.]])

相比之下,np.zeros(1, 2) 引发 TypeError

In [117]: np.zeros(1, 2)
TypeError: data type not understood

因为 the second argument to np.zeros 应该是 dtype,而 2 不是值 dtype


或者,要创建一个包含一个 int 和一对 int 的自定义 dtype 的一维数组,您可以使用

In [120]: np.zeros((2,), dtype=[('x', 'i4'), ('y', '2i4')])
Out[120]: 
array([(0, [0, 0]), (0, [0, 0])], 
      dtype=[('x', '<i4'), ('y', '<i4', (2,))])

虽然我不会推荐这个。如果这些值都是整数,我认为你最好使用一个具有同质整数 dtype 的简单 ndarray,也许是形状 (nrows, 3):

In [121]: np.zeros((2, 3), dtype='<i4')
Out[121]: 
array([[0, 0, 0],
       [0, 0, 0]], dtype=int32)

一般来说,我发现使用具有简单 dtype 的数组可以使从构建数组到切片和整形的许多操作变得更容易。

【讨论】:

  • 我想你误解了我的问题。我不是在寻找整数矩阵。我需要一个看起来像 [int, [[int,int]]] 的矩阵。一个矩阵,第一列为整数,第二列为整数列表
  • 刷新您的页面。我在回答的第二部分提到了这个问题。
  • 这更接近我正在寻找的东西。但是,我希望第二列支持点列表。虽然它目前只支持 1 点。
  • 除非我没有将每个点分开到他们自己的列表中
  • 我认为您为这个问题提供的答案可能有效。 stackoverflow.com/questions/2106287/…
猜你喜欢
  • 2013-03-17
  • 2013-02-09
  • 2018-02-16
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多