制表符分隔的数组到numpy数组的列表?

2024-10-03 04:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

Win 7,x64,Python 2.7.12

我有表格里的数据

myData = [[a1, b1, c1, d1, e1, f1, g1, h1], [a2, b2, c2, .... ], ..... ]

其中myData是浮点数的np.ndarray。我用下面的方法保存了这个。。。在

^{pr2}$

在检查的时候,它被保存得像。。。在

[a1   b1   c1   d1   e1   f1   g1   h1]
[a2   b2   c2   d2   e2   f2   g2   h1]
.....

即制表符分隔。在

所以我试着用。。。在

import numpy as np
from ast import literal_eval

with open('myData.txt', 'r') as f:
    fromFile = [np.ndarray(literal_eval(line)) for line in f]
f.close()

但这会带来一个错误。。。在

  File "<unknown>", line 1
    [ 1.     1.198  2.063  1.833  1.458  1.885  1.969  0.343]
                 ^
SyntaxError: invalid syntax

既然我不能重新生成文件myData.txt,如何将其还原为其初始数据类型?在

还有没有一种方法可以阻止数据在一开始就被写出来?在

编辑:以上问题的解决方案。。。在

import numpy as np
from ast import literal_eval

branches = ['[ 1.     1.198  2.063  1.833  1.458  1.885  1.969  0.343]\n', 
            '[ 2.    1.26  2.    1.26  1.26  2.    1.26  0.  ]\n', 
            '[ 3.     1.688  2.     1.781  1.573  2.021  1.979  0.23 ]\n', 
            '[ 4.     1.604  2.729  1.792  1.667  2.49   1.948  0.293]\n']

branches = [line.rstrip(']\n') for line in branches]
branches = [line.lstrip('[ ') for line in branches]
print branches[0]

branches = [line.split('  ') for line in branches]
newBranches = []
for branch in branches:
    branch = filter(None, branch)
    branch = [float(item) for item in branch]
    newBranches.append(branch)

print newBranches[0]

branches = np.array(newBranches)

除非有更快的方法来做,否则我会这么做的。我也将采纳尼尔斯沃纳的建议在下面的答案。在


Tags: 数据方法inimportbranchforaseval