2017-08-19 85 views
1

矩阵我有一个这样的名单:创建一个列表蟒蛇

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: list index out of range

我应该怎么办?

+0

你能提供一个小的,但可重现的输入数据集和你想要的数据集吗? – MaxU

+0

可能重复[如何从Python中的列表构造矩阵?](https://stackoverflow.com/questions/29224148/how-to-construct-a-matrix-from-lists-in-python) – manelfp

+1

什么是“a_00”,“a_01”等类型?字符串或数字? – Psidom

回答

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. 
+0

谢谢,这对我有用。 – mahsa

+0

欢迎您@mahsa :) –

+0

我会用#B [item [1],item [2]]' – hpaulj

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]]) 
+0

这是非常优雅的,但我相信OP想要一个不同的结果集... – MaxU

+0

@MaxU嗯。我也只是测试了Vikash的数据集。似乎给出了相同的结果。 – Psidom

+0

我想知道为什么我们在结果集中看到所有这些零... – MaxU

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') 
+0

这也是有效的。 – mahsa