2

我有一个这样的矩阵,想将其转换为数组进行处理。怎么做

[[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]]

我知道它应该是形式

[[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]]

通常我正在做的是将我的数组手动转换为上述形式并调用

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]])
4

2 回答 2

1

我不确定导入矩阵时的格式是什么,这里是基于字符串的矩阵的解决方案。

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]]

或在一行中:

ast.literal_eval(", ".join(s.replace(" [","[").replace("[ ","[").split()))
于 2020-09-10T02:20:28.047 回答
0

假设矩阵存储在一个字符串上并且它总是整数,你可以这样做:

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)

在这种情况下,

>>> 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]])
于 2020-09-10T02:20:02.427 回答