将numpy数组值转换为整数

2024-04-29 22:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 类型数组float64e09
2条回答

制作一个示例数组

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

我们可以转换成ints,但是注意最大的一个太大了默认的int32

^{pr2}$

使用默认格式(float)写入csv(这是默认格式,而不考虑数组数据类型):

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个问题:

  • 整数v在数组本身中是dtype
  • 显示或打印阵列
  • 将数组写入csv文件

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

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

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

相关问题 更多 >