Convert a list of lists to array type in Python

163 Views Asked by At

I have a matrix like this and want to convert it to array for processing. How to do it

[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]

I understand that it should be of the form

[[25,  3,  0,  1,  0,  2,  1],
 [ 1, 21,  0,  0,  0,  0,  0],
 [ 0,  3, 18,  0,  0,  0,  0],
 [ 1,  0,  0, 35,  2,  0,  0],
 [ 0,  0,  0,  4, 27,  2,  0],
 [ 0,  0,  0,  0,  1, 27,  0],
 [ 1,  1,  0,  0,  0,  0, 34]]

Usually what i am doing is convert my array to the above form manually and calling

class = np.array([[28,  3,  0,  0,  5,  2,  1],
 [ 6, 25 , 0,  2,  2,  8,  0],
 [ 0 , 1 ,51 , 0,  0,  0,  0],
 [ 5 , 2 , 0 ,25, 12,  2,  2],
 [ 1 , 0 , 0,  2, 40,  6,  0],
 [ 0 , 0 , 0  ,0,  1, 48,  0],
 [ 2 , 1,  0  ,0 , 1,  1, 51]])
2

There are 2 best solutions below

0
On

I am not sure what format you have when importing the matrix, here a solution for a string based matrix.

from ast import literal_eval

s = '''
[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]
'''
s = s.replace(" [","[").replace("[ ","[")
s = ", ".join(s.split())
ast.literal_eval(s)

# Out[12]: 
# [[25, 3, 0, 1, 0, 2, 1],
#  [1, 21, 0, 0, 0, 0, 0],
#  [0, 3, 18, 0, 0, 0, 0],
#  [1, 0, 0, 35, 2, 0, 0],
#  [0, 0, 0, 4, 27, 2, 0],
#  [0, 0, 0, 0, 1, 27, 0],
#  [1, 1, 0, 0, 0, 0, 34]]

or in one line:

ast.literal_eval(", ".join(s.replace(" [","[").replace("[ ","[").split()))
0
On

Assuming that the matrix is stored on a string and it will always be integers, you can do:

import re
import numpy as np

my_list = """
[[25  3  0  1  0  2  1]
 [ 1 21  0  0  0  0  0]
 [ 0  3 18  0  0  0  0]
 [ 1  0  0 35  2  0  0]
 [ 0  0  0  4 27  2  0]
 [ 0  0  0  0  1 27  0]
 [ 1  1  0  0  0  0 34]]
"""

rows = []

for line in filter(len, map(str.strip, my_list.split("\n"))):
    rows.append([ int(v) for v in re.findall(r"\b[0-9]+\b", line) ])

np_rows = np.array(rows)

In that case,

>>> np_rows
array([[25,  3,  0,  1,  0,  2,  1],
       [ 1, 21,  0,  0,  0,  0,  0],
       [ 0,  3, 18,  0,  0,  0,  0],
       [ 1,  0,  0, 35,  2,  0,  0],
       [ 0,  0,  0,  4, 27,  2,  0],
       [ 0,  0,  0,  0,  1, 27,  0],
       [ 1,  1,  0,  0,  0,  0, 34]])