为什么 numpy 数组将 int 变成 float [英] Why do numpy array turns int into float
本文介绍了为什么 numpy 数组将 int 变成 float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用整数填充数组,但似乎 numpy 数组一直在将整数转换为浮点数.为什么会发生这种情况,我该如何阻止?
arr = np.empty(9)arr[3] = 7打印(arr [3])>>>7.0
解决方案
NumPy 数组与 Python 列表不同,只能包含单一类型,(据我所知)在创建时设置.您放入数组的所有内容都会转换为该类型.
默认情况下,数据类型假定为 float
.要设置另一种类型,您可以将 dtype
传递给 empty
函数,如下所示:
I'm trying to fill an array with integers, but it seems like numpy array keep turning the integers into floats. Why is this happening and how do I stop this?
arr = np.empty(9)
arr[3] = 7
print(arr[3])
>>>7.0
解决方案
NumPy arrays, unlike Python lists, can contain only a single type, which (as far as I know) is set at creation time. Everything you put into the array gets converted to that type.
By default, the data type is assumed to be float
. To set another type, you can pass dtype
to the empty
function like this:
>>> arr = np.empty(9, dtype=int)
>>> arr[3] = 7
>>> arr[3]
7
这篇关于为什么 numpy 数组将 int 变成 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文