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

标签 python numpy

我想知道如何将在此问题的答案(由 Paul)中创建的数组保存到文本文件中。

How do I print an aligned numpy array with (text) row and column labels?

详情如下:

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

最佳答案

我真的很喜欢使用 writelines 的 repr() 和 .rjust() 功能。假设我有一个 Matrix '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()

关于python - 如何将包含多个字符串的 python 数组保存到人类可读的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827176/

相关文章:

python - python 的简单 QR 迭代的特征值不正确

python - 在 with None : what if it's an array? 之后定义默认参数

python - 如何从oracle游标的输出中添加转义字符串?

python - 将 numpy 数组追加到元素中

python - Numba 和泊松分布的随机数

python - 英雄库/Django : No module named dj_database_url

Numpy不准确的矩阵求逆

python - 单击链接时阻止 selenium 打开新窗口

Python 处理 TypeError :

python - 在 pandas 中使用 shift 和 rolling 与 groupBy