【问题标题】:Numpy Saving Text IncorrectlyNumpy 错误地保存文本
【发布时间】:2016-02-11 23:20:49
【问题描述】:

我目前正在编写一个 python 3 函数,该函数接受一个 numpy 数组并将整个数组打印到一个文本文件,但它首先将 0 附加到最后一行。例如,如果我给它 np.eye(3),

1 0 0 
0 0 1
0 0 1

它应该写,

1 0 0 
0 0 1
0 0 1 0

到一个文本文件。虽然下面的代码,

def addTo(array,textFile):
  file=open(textFile,'ab')
  (numRows,numColumns)=array.shape
  main=array[0:numRows-1,:]
  endRow=array[numRows-1,:]
  newEndRow=np.append(endRow, [0])
  np.savetxt(file,main, fmt='%10.5f', newline=os.linesep)
  np.savetxt(file,newEndRow[np.newaxis], fmt='%10.5f', newline=os.linesep)
  file.close()

addTo(np.eye(3),'test1.txt')  

不断返回

   1.00000    0.00000    0.00000
   0.00000    1.00000    0.00000
   0.00000    0.00000    1.00000    0.00000

这很奇怪,因为文本文件中的每一行都是缩进的。有没有办法阻止 numpy 这样做?

【问题讨论】:

标签: arrays python-3.x numpy text-files


【解决方案1】:

是什么让你烦恼?您的格式指定一个 10 字符长的字段,包含 5 个小数。这就是你得到的:

In [357]:  fmt='%10.5f'
In [358]: fmt%1
Out[358]: '   1.00000'
In [359]: fmt%0
Out[359]: '   0.00000'

要获得'1 0 0',您需要给它一个不同的fmt,例如%d。您熟悉 Python 格式 % 规范吗?

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2017-04-17
    • 2021-01-02
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多