首页 > 解决方案 > 如何将浮点类型的 numpy 数组转换为 int 类型的 numpy 数组?

问题描述

我有以下源代码:

npW_x = np.array(my_np_array)
npW_round_111 = np.around(npW_x, decimals=0)
sum_x_111 = np.sum(npW_round_111, axis=1)

np.savetxt("file1.txt", sum_x_111)

文件输出

3.200000000000000000e+01
5.500000000000000000e+01
3.300000000000000000e+01
4.900000000000000000e+01
5.200000000000000000e+01
5.500000000000000000e+01
3.800000000000000000e+01
5.200000000000000000e+01
5.100000000000000000e+01
3.100000000000000000e+01
3.100000000000000000e+01
3.200000000000000000e+01
5.100000000000000000e+01
... ... ... ... ... ...

预期输出如下:

3
6
3
5
5
6
4
5
5
3
3
3
5
... ... ... ... ... ...

我怎样才能做到这一点?

标签: pythonnumpyrounding

解决方案


In [385]: npW_x = np.random.rand(4,5)*10
     ...: npW_round_111 = np.around(npW_x, decimals=0)
     ...: sum_x_111 = np.sum(npW_round_111, axis=1)
     ...: 
In [386]: sum_x_111
Out[386]: array([38., 25., 24., 30.])

保存为默认值fmt(阅读并重新阅读np.savetxt文档!)

In [387]: np.savetxt('test',sum_x_111)
In [388]: cat test
3.800000000000000000e+01
2.500000000000000000e+01
2.400000000000000000e+01
3.000000000000000000e+01

以 int 格式保存:

In [389]: np.savetxt('test',sum_x_111, fmt='%10d')
In [390]: cat test
        38
        25
        24
        30

在内存中转换为 int:

In [391]: In [391]: sum_x_111.astype(int)
Out[391]: array([38, 25, 24, 30])

推荐阅读