有没有更好的方法来阅读numpy矩阵?

时间:2018-03-23 08:43:32

标签: python numpy matrix

我的文本文件包含这样的矩阵

[ 1 2 3 4 5 6 7 8 9 10
  11 12 13] [ 14 15 16
  17 18 19 20 21 22 23]

我需要一种更快速的方法来将矩阵读入numpy。我使用reg将矩阵与空格分开,然后']'分别读入一个numpy数组,这是一个繁琐的过程。我需要将它存储在numpy中:

[[ 1 2 3 4 5 6 7 8 9 10 11 12 13], [ 14 15 16 17 18 19 20 21 22 23]]

1 个答案:

答案 0 :(得分:1)

你不能在numpy中得到这个,因为你的数组有不同长度的行。

这是一种将输入转换为列表列表的强力方法:

import pandas as pd
from io import StringIO
from ast import literal_eval

mystr = StringIO("""[ 1 2 3 4 5 6 7 8 9 10
  11 12 13] [ 14 15 16
  17 18 19 20 21 22 23]""")

# replace mystr with 'file.csv'
df = pd.read_csv(mystr, header=None)

res = '[' + ''.join([x.replace('  ', ',').replace('[ ', '[')\
                     .replace(' ', ',').replace('][', '],[') for x in df[0]]) + ']'

lst = literal_eval(res)

# [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
#  [14, 15, 16, 17, 18, 19, 20, 21, 22, 23]]