首页 > 解决方案 > 如何将元组列表列表(索引,值)转换为 2D numpy 数组

问题描述

有元组列表列表:

[[(0, 0.5), (1, 0.6)], [(4, 0.01), (5, 0.005), (6, 0.002)], [(1,0.7)]]

我需要得到矩阵 X x Y:

x = num of sublists
y = max among second eleme throught all pairs
elem[x,y] = second elem for x sublist if first elem==Y 
0 1 2 3 4 5 6
0.5 0.6 0 0 0 0 0
0 0 0 0 0.01 0.005 0.002
0 0.7 0 0 0 0 0

标签: pythonlistnumpytuples

解决方案


您可以通过以下方式计算数组的尺寸。Y维度是子列表的数量

>>> data = [[(0, 0.5), (1, 0.6)], [(4, 0.01), (5, 0.005), (6, 0.002)], [(1,0.7)]]
>>> dim_y = len(data)
>>> dim_y
3

X 维度是[0]所有元组的最大索引加 1。

>>> dim_x = max(max(i for i,j in sub) for sub in data) + 1
>>> dim_x
7

所以然后用这个大小初始化一个全零的数组

>>> import numpy as np
>>> arr = np.zeros((dim_x, dim_y))
>>> arr
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

现在填充它,enumerate在您的子列表上跟踪 y 索引。然后对于每个子列表,使用[0]x 索引和[1]值本身

for y, sub in enumerate(data):
    for x, value in sub:
        arr[x,y] = value

然后应该填充生成的数组(可能想要转置以看起来像您想要的尺寸)。

>>> arr.T
array([[0.5  , 0.6  , 0.   , 0.   , 0.   , 0.   , 0.   ],
       [0.   , 0.   , 0.   , 0.   , 0.01 , 0.005, 0.002],
       [0.   , 0.7  , 0.   , 0.   , 0.   , 0.   , 0.   ]])

推荐阅读