在 numpy.savetxt 中设置 fmt 选项 [英] Setting the fmt option in numpy.savetxt

查看:83
本文介绍了在 numpy.savetxt 中设置 fmt 选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 numpy.savetxt,并被困在 fmt 选项上.

I am looking at the numpy.savetxt, and am stuck at the fmt option.

我尝试查看 此处 以及中的参考可用于 fmt 选项排序的所​​有字母下方的链接让我大致了解正在发生的事情.

I tried looking at here and also the reference in the link below all the letters that can be used for the fmt option sort give me a general sense of what is going on.

我不明白的是 % 符号是否是必需的,并且在一个例子中给出了 这里 我应该如何解释 10.5 数字?如果f"是关于设置浮点数,那怎么会是10.5(再说一次,我可能不知道浮点数是如何设置的......).

What I do not understand is if the % symbol is required and in an example given here how should I interpret the 10.5 number? If "f" is about setting the floating point, then how come is it 10.5 (then again, I might not know how floating points are set...).

推荐答案

知道 np.savetxt 只适用于一维或二维数组,大致思路是:

Knowing that np.savetxt only works for 1D or 2D arrays, the general idea is:

  • fmt 是单个格式化字符串时,它适用于数组(一维或二维输入数组)
  • fmt是格式化字符串序列时,它适用于二维输入数组的每一列
  • when fmt is a single formatting string it applies to all elements in the array (1D or 2D input array)
  • when fmt is a sequence of formatting strings, it applies to each column of the 2D input array

我在这里展示了一些使用以下输入数组的示例:

I'm presenting here some examples using the following input array:

import numpy as np

a = np.array([[11, 12, 13, 14],
              [21, 22, 23, 24],
              [31, 32, 33, 34]])

1) 设置浮点精度:np.savetxt('tmp.txt', a, fmt='%1.3f')

11.000 12.000 13.000 14.000
21.000 22.000 23.000 24.000
31.000 32.000 33.000 34.000

2) 添加字符以右对齐.

2) Adding characters to right-justify.

带空格:np.savetxt('tmp.txt', a, fmt='% 4d')

  11   12   13   14
  21   22   23   24
  31   32   33   34

带零:np.savetxt('tmp.txt', a, fmt='%04d')

0011 0012 0013 0014
0021 0022 0023 0024
0031 0032 0033 0034

3) 向左对齐添加字符(使用-").

3) Adding characters to left-justify (use of "-").

带空格:np.savetxt('tmp.txt', a, fmt='%-4d')

11   12   13   14  
21   22   23   24  
31   32   33   34  

4) 当fmt为格式化字符串序列时,二维输入数组的每一行都按照fmt进行处理:

4) When fmt is a sequence of formatting strings, each row of a 2D input array is processed according to fmt:

fmt 作为单个格式化字符串中的序列

fmt = '%1.1f + %1.1f / (%1.1f * %1.1f)'
np.savetxt('tmp.txt', a, fmt=fmt)

11.0 + 12.0 / (13.0 * 14.0)
21.0 + 22.0 / (23.0 * 24.0)
31.0 + 32.0 / (33.0 * 34.0)

fmt 作为格式化字符串的迭代器:

fmt = '%d', '%1.1f', '%1.9f', '%1.9f'
np.savetxt('tmp.txt', a, fmt=fmt)

11 12.0 13.000000000 14.000000000
21 22.0 23.000000000 24.000000000
31 32.0 33.000000000 34.000000000

这篇关于在 numpy.savetxt 中设置 fmt 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆