【问题标题】:Converting numpy array values into integers将numpy数组值转换为整数
【发布时间】:2017-03-19 17:18:47
【问题描述】:

我的值目前在数组中显示为1.00+e09(float64 类型)。我希望他们改为显示1000000000。这可能吗?

【问题讨论】:

  • 您到底想使用float64,还是希望数据实际上只是整数?
  • 我希望它们是整数。我试图在一些计算后将值写回 csv 文件,然后将 csv 文件转换为 excel 文件。现在,我的 excel 文件中的值显示为 1.00+e09 形式,我无法在 excel 上使用。

标签: python numpy


【解决方案1】:

制作一个样本数组

In [206]: x=np.array([1e9, 2e10, 1e6])
In [207]: x
Out[207]: array([  1.00000000e+09,   2.00000000e+10,   1.00000000e+06])

我们可以转换成 int - 除了注意最大的 int32 比默认的 int32 太大

In [208]: x.astype(int)
Out[208]: array([ 1000000000, -2147483648,     1000000])

In [212]: x.astype(np.int64)
Out[212]: array([ 1000000000, 20000000000,     1000000], dtype=int64)

使用默认格式 (float) 编写 csv(这是默认格式,与数组 dtype 无关):

In [213]: np.savetxt('text.txt',x)
In [214]: cat text.txt
1.000000000000000000e+09
2.000000000000000000e+10
1.000000000000000000e+06

我们可以指定格式:

In [215]: np.savetxt('text.txt',x, fmt='%d')
In [216]: cat text.txt
1000000000
20000000000
1000000

可能有3个问题:

  • integer v float 在数组本身中,它是dtype
  • 数组的显示或打印
  • 将数组写入 csv 文件

【讨论】:

  • 谢谢,这有助于加载。 :)
【解决方案2】:

这是一个打印选项,请参阅文档:printing options。简要说明:打印时需要使用suppress选项:

np.set_printoptions(suppress=True)  # for small floating point.

np.set_printoptions(suppress=True, formatter={'all':lambda x: str(x)})

【讨论】:

  • 但重读suppress。它与小浮点的显示有关,而不是大浮点。例如1e-9.
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2021-12-29
  • 2017-03-08
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多