python - 如何将浮点类型的 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
... ... ... ... ... ...
我怎样才能做到这一点?
解决方案
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])
推荐阅读
- ios - 如果应用程序由本地通知启动,则访问通知有效负载
- javascript - 如何确定一个点是否在其他两个点之间?
- c++ - std::copy、std::copy_backward 和重叠范围
- python - 遍历 Pandas Dataframe 中的两个变量
- android-studio - Is there a simple way to convert lambda into a full expression in Kotlin with Android Studio 3.5.1?
- python-3.x - 在python返回函数中返回多个值
- python - 修复python中左等腰三角形和右等腰三角形的代码
- c - 又是一个关于用 C 读取目录文件的问题
- javascript - 如何在两个表之间使用 sequelize 创建嵌套请求
- javascript - 带有正则表达式积极前瞻的 Firefox 错误?