将 lists 的 list 转换为一个 numpy 矩阵
程序员文章站
2022-06-14 23:00:12
...
如题,要是 list of lists 中,所有的 子 list
的长度都相同,那就比较好办。
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
y = np.hstack(x)
num_rows = len(x)
matrix = y.reshape(num_rows, -1)
如果 list of lists 中,子 list
的长度不全相等,那我们需要用 None
去填白:
x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
matrix = np.array([xi+[None]*(length-len(xi)) for xi in x])
可得如下:
array([[1, 2, None],
[1, 2, 3],
[1, None, None]], dtype=object)