从python中的列表创建一个矩阵

时间:2017-08-19 18:47:27

标签: python arrays numpy

我有一个这样的清单:

A=[["a_00",0,0],["a_01",0,1],["a_02",0,2],["a_03",0,3], ["a_10",1,0],["a_11",1,1],["a_12",1,2],["a_13",1,3], ["a_20",2,0],["a_21",2,1],["a_22",2,2],["a_23",2,3], ["a_30",3,0],["a_31",3,1],["a_32",3,2],["a_33",3,3]]

产生:

In [187]: A
Out[187]:
[['a_00', 0, 0],
 ['a_01', 0, 1],
 ['a_02', 0, 2],
 ['a_03', 0, 3],
 ['a_10', 1, 0],
 ['a_11', 1, 1],
 ['a_12', 1, 2],
 ['a_13', 1, 3],
 ['a_20', 2, 0],
 ['a_21', 2, 1],
 ['a_22', 2, 2],
 ['a_23', 2, 3],
 ['a_30', 3, 0],
 ['a_31', 3, 1],
 ['a_32', 3, 2],
 ['a_33', 3, 3]]

我想转到这样的矩阵:

B=[["a_00","a_01","a_02","a_03"], ["a_10","a_11","a_12","a_13"], ["a_20","a_21","a_22","a_23"], ["a_30","a_31","a_32","a_33"]] 

的产率:

In [188]: B
Out[188]:
[['a_00', 'a_01', 'a_02', 'a_03'],
 ['a_10', 'a_11', 'a_12', 'a_13'],
 ['a_20', 'a_21', 'a_22', 'a_23'],
 ['a_30', 'a_31', 'a_32', 'a_33']]

我为了我的目的写了这段代码:

import numpy
B=numpy.zeros(7,7)
for item in A:
    B[item[1]][item[2]]=item[0]

但我看到了这个错误:

  

IndexError:列表索引超出范围

我该怎么办?

3 个答案:

答案 0 :(得分:2)

您的代码似乎没有问题,除了1行B=numpy.zeros(7,7)它应该是B=numpy.zeros((7,7))

根据documentation

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

import numpy as np

B = np.zeros((3,3))
for item in A:
    B[item[1]][item[2]]=item[0]

B

array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

您也可以使用重塑

以简单的方式完成
np.array(A)[:,0].reshape(7,7)

如何运作:

np.array(A)
array([[a_00, 0, 0],
       [a_01, 0, 1],
       [a_02, 0, 2],
       ...

np.array(A)[:,0]
array([a_00, a_01, a_02,...])

np.array(A)[:,0].reshape(3,3) # reshape it in the shape that we care for.

答案 1 :(得分:2)

列表以稀疏矩阵的格式存储,您可以分别提取值,行和列索引,然后使用scipy.sparse.coo_matrix从中构造稀疏矩阵:

lst = [[3,0,0],[2,0,1],[1,0,6],
       [5,1,0],[3,1,1],[2,1,6],
       [7,6,0],[5,6,1],[7,6,6]]

from scipy.sparse import coo_matrix

v, i, j = zip(*lst)
coo_matrix((v, (i, j)), shape=(7,7)).toarray()

#array([[3, 2, 0, 0, 0, 0, 1],
#       [5, 3, 0, 0, 0, 0, 2],
#       [0, 0, 0, 0, 0, 0, 0],
#       [0, 0, 0, 0, 0, 0, 0],
#       [0, 0, 0, 0, 0, 0, 0],
#       [0, 0, 0, 0, 0, 0, 0],
#       [7, 5, 0, 0, 0, 0, 7]])

使用@ Vikash的数据:

v, i, j = zip(*A)
coo_matrix((v, (i, j)), shape=(3,3)).toarray()
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

答案 2 :(得分:2)

IIUC:

In [185]: a,b,c = zip(*A)

In [186]: np.array(a).reshape(np.unique(b).size, -1)
Out[186]:
array([['a_00', 'a_01', 'a_02', 'a_03'],
       ['a_10', 'a_11', 'a_12', 'a_13'],
       ['a_20', 'a_21', 'a_22', 'a_23'],
       ['a_30', 'a_31', 'a_32', 'a_33']],
      dtype='<U4')