【问题标题】:numpy.savetxt - Save a np.array with different typesnumpy.savetxt - 保存具有不同类型的 np.array
【发布时间】:2020-11-30 12:24:51
【问题描述】:

这个问题与其他已经存在的问题有关(例如this),但我无法按照那里提供的解决方案来解决。所以我试着再问一次。

我有 7 个参数,例如 a1a2b1b2b3b4b5。 'a' 参数是整数,而 'b' 参数是浮点数。 以

为例
a1=1, a2=500, b1=1.0, b2=1.0, b3=-0.866025, b4=0.0, b5=-0.1.

我想将这些参数保存到一个文件中。执行此操作的代码如下:

f = open("params.txt",'w')
arr=np.array((a1,a2,b1,b2,b3,b4,b5))
arrform=' '.join(['%d']*2 + ['%f']*5)
np.savetxt(f,arr,fmt=arrform)
f.close()

执行此代码时,我收到以下错误消息:

fmt has wrong number of % formats: %d %d %f %f %f %f %f

请你告诉我我的错误是什么?

【问题讨论】:

  • print(arrform%(a1,a2,...), file=f) of f.write(...) 如果这些变量是标量就足够了。您不需要numpy 来格式化和编写数字元组。

标签: python arrays numpy format save


【解决方案1】:

使用 column_stack 代替数组

f = open("params.txt",'w')
arr=np.column_stack((a1,a2,b1,b2,b3,b4,b5))
arrform=' '.join(['%d']*2 + ['%f']*5)
np.savetxt(f,arr,fmt=arrform)
f.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-06
    • 2018-06-21
    • 2013-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多