numpy 在python中将平面列表读入多维数组/矩阵

s2j5cfk0  于 2022-11-23  发布在  Python
关注(0)|答案(5)|浏览(140)

我有一个数字列表,表示由另一个程序生成的矩阵或数组的扁平化输出,我知道原始数组的维数,并希望将数字读回到列表列表列表或NumPy矩阵中。原始数组中可能有二维以上。
例如:

data = [0, 2, 7, 6, 3, 1, 4, 5]
shape = (2,4)
print some_func(data, shape)

会产生:
[[0,2,7,6],[3,1,4,5]]
提前干杯

b1uwtaje

b1uwtaje1#

使用numpy.reshape

>>> import numpy as np
>>> data = np.array( [0, 2, 7, 6, 3, 1, 4, 5] )
>>> shape = ( 2, 4 )
>>> data.reshape( shape )
array([[0, 2, 7, 6],
       [3, 1, 4, 5]])

如果要避免在内存中复制datashape属性,也可以直接将其赋值:

>>> data.shape = shape
ajsxfq5m

ajsxfq5m2#

如果你不想使用numpy,有一个简单的2d例子:

group = lambda flat, size: [flat[i:i+size] for i in range(0,len(flat), size)]

并且可以通过添加递归来推广到多维:

import operator
def shape(flat, dims):
    subdims = dims[1:]
    subsize = reduce(operator.mul, subdims, 1)
    if dims[0]*subsize!=len(flat):
        raise ValueError("Size does not match or invalid")
    if not subdims:
        return flat
    return [shape(flat[i:i+subsize], subdims) for i in range(0,len(flat), subsize)]
w80xi6nr

w80xi6nr3#

对于那些俏皮话:

>>> data = [0, 2, 7, 6, 3, 1, 4, 5]
>>> col = 4  # just grab the number of columns here

>>> [data[i:i+col] for i in range(0, len(data), col)]
[[0, 2, 7, 6],[3, 1, 4, 5]]

>>> # for pretty print, use either np.array or np.asmatrix
>>> np.array([data[i:i+col] for i in range(0, len(data), col)]) 
array([[0, 2, 7, 6],
       [3, 1, 4, 5]])
j2cgzkjk

j2cgzkjk4#

如果没有Numpy,我们也可以做如下..

l1 = [1,2,3,4,5,6,7,8,9]

def convintomatrix(x):

    sqrt = int(len(x) ** 0.5)
    matrix = []
    while x != []:
        matrix.append(x[:sqrt])
        x = x[sqrt:]
    return matrix

print (convintomatrix(l1))
nbysray5

nbysray55#

[list(x) for x in zip(*[iter(data)]*shape[1])]


(在搜索如何工作时找到this post

相关问题