简体   繁体   English

如何将带有多个字符串的python数组保存到人类可读的文件中

[英]How to save a python array with numbers of strings to a file that is human readable

I would like to know how to save the array created in this question's answer (by Paul) to a text file. 我想知道如何将在这个问题的答案中(保罗提出)创建的数组保存到文本文件中。

How do I print an aligned numpy array with (text) row and column labels? 如何打印带有(文本)行和列标签的对齐的numpy数组?

The details are: 详细信息是:

a = np.random.rand(5,4)
x = np.array('col1 col2 col3 col4'.split())
y = np.array('row1 row2 row3 row4 row5'.split())
b = numpy.zeros((6,5),object)
b[1:,1:]=a
b[0,1:]=x
b[1:,0]=y
b[0,0]=''
printer = np.vectorize(lambda x:'{0:5}'.format(x,))
print printer(b).astype(object)

[[     col1 col2 col3 col4]
 [row1 0.95 0.71 0.03 0.56]
 [row2 0.56 0.46 0.35 0.90]
 [row3 0.24 0.08 0.29 0.40]
 [row4 0.90 0.44 0.69 0.48]
 [row5 0.27 0.10 0.62 0.04]]

The way you go about it depends on how you intend to access it. 处理方式取决于您打算如何使用它。 Since you want it human readable, the easy solution is to print it to a file. 由于您希望它易于阅读,因此简单的解决方案是将其打印到文件中。 That does make it more difficult to restore from the file though. 但这确实使从文件还原更加困难。

f = open(Filename, 'w')
f.write(str(printer(b).astype(object)))
f.flush()
f.close()

I really like to use the repr() and .rjust() functionality of writelines. 我真的很喜欢使用writelines的repr()和.rjust()功能。 So let's say I have a Matrix 'mat' (ie an ndarray) where A.shape = (10,2), and would like certain formatting and rounding, I can get a decent, adjusted output by using the following: 假设我有一个矩阵'mat'(即ndarray),其中A.shape =(10,2),并且想要进行某些格式设置和舍入,我可以通过使用以下命令得到一个不错的调整后的输出:

mat = numpy.random.rand(10,10)
f = open('myFile','a')
m,n = mat.shape
for i in range(0,m):
    for j in range(0,n):
        f.writelines(repr(round(mat[i,j],4)).rjust(7))
f.writelines('\n')

f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM