Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用empty()函数创建具有int值的ndarray?_Python_Ipython - Fatal编程技术网

Python 如何使用empty()函数创建具有int值的ndarray?

Python 如何使用empty()函数创建具有int值的ndarray?,python,ipython,Python,Ipython,问题是,每当我键入ndarray时,它都会以浮点形式给出值。我只想要int格式的输出 我试过y=int(y1) 但它显示了TypeError:只有size-1数组可以转换为Python标量 var = (4, 5, 6) length = len(var) print(length) from numpy import empty y1 = empty([len(var)]) y = int(y1) print(y) i = 0 for x in var: print(x)

问题是,每当我键入ndarray时,它都会以浮点形式给出值。我只想要int格式的输出

我试过y=int(y1) 但它显示了TypeError:只有size-1数组可以转换为Python标量

var = (4, 5, 6)
length = len(var)
print(length)
from numpy import empty

y1 = empty([len(var)])
y = int(y1)
print(y)

i = 0
for x in var:
    print(x)
    print("i = %i" % i)
    y[i] = int(x)
    print(y[i])
    i = i + 1
print(var)
print(y)

我只想要int类型的输出,而不是float类型的输出。我还尝试在每次赋值时在for循环内部更改数据类型。有更好的方法吗?

您可以这样指定
数据类型:

>>> import numpy as np
>>> np.empty((3,5), dtype=np.int)
array([[ 805306368, -244667706,  382337028,  979432584,  360625744],
       [ 357830816,  357820336,  979432584,  979432576,  360007872],
       [ 382203840,  382204224,  382476528,  379622304,  357830816]])

您可以这样指定
dtype

>>> import numpy as np
>>> np.empty((3,5), dtype=np.int)
array([[ 805306368, -244667706,  382337028,  979432584,  360625744],
       [ 357830816,  357820336,  979432584,  979432576,  360007872],
       [ 382203840,  382204224,  382476528,  379622304,  357830816]])

要创建具有特定类型的空numpy数组,请使用:

import numpy as np
shape = (1,2,3)
arr = np.empty(shape=shape, dtype=np.int32)

要创建具有特定类型的空numpy数组,请使用:

import numpy as np
shape = (1,2,3)
arr = np.empty(shape=shape, dtype=np.int32)

dtype
在创建数组时确定。作业不会改变这一点。考虑到您目前的理解水平,我认为创建一个
np.zeros(3,dtype=int)
是一个更好的主意。或者
np.array(var)
dtype
问题是相同的,但它减少了对数组初始值的混淆。
dtype
是在创建数组时确定的。作业不会改变这一点。考虑到您目前的理解水平,我认为创建一个
np.zeros(3,dtype=int)
是一个更好的主意。或者
np.array(var)
dtype
问题是相同的,但它减少了对数组初始值的混淆。