Python 使用 NumPy 的数据类型的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16972501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:07:32  来源:igfitidea点击:

Size of data type using NumPy

pythonnumpy

提问by mgilson

In NumPy, I can get the size (in bytes) of a particular data type by:

在 NumPy 中,我可以通过以下方式获取特定数据类型的大小(以字节为单位):

datatype(...).itemsize

or:

或者:

datatype(...).nbytes

For example:

例如:

np.float32(5).itemsize #4
np.float32(5).nbytes   #4

I have two questions. First, is there a way to get this information without creating an instanceof the datatype? Second, what's the difference between itemsizeand nbytes?

我有两个问题。首先,有没有办法在不创建数据类型实例的情况下获取这些信息?二,什么是之间的区别itemsizenbytes

采纳答案by Joe Kington

You need an instance of the dtypeto get the itemsize, but you shouldn't need an instance of the ndarray. (As will become clear in a second, nbytesis a property of the array, not the dtype.)

您需要一个 的实例dtype来获取项目大小,但您不应该需要ndarray. (稍后会变得清楚,nbytes是数组的属性,而不是 dtype。)

E.g.

例如

print np.dtype(float).itemsize
print np.dtype(np.float32).itemsize
print np.dtype('|S10').itemsize

As far as the difference between itemsizeand nbytes, nbytesis just x.itemsize * x.size.

至于itemsize和之间的区别nbytesnbytes就是x.itemsize * x.size

E.g.

例如

In [16]: print np.arange(100).itemsize
8

In [17]: print np.arange(100).nbytes
800

回答by dawg

Looking at the NumPy C source file, this is the comment:

查看 NumPy C 源文件,这是注释:

size : int
    Number of elements in the array.
itemsize : int
    The memory use of each array element in bytes.
nbytes : int
    The total number of bytes required to store the array data,
    i.e., ``itemsize * size``.

So in NumPy:

所以在 NumPy 中:

>>> x = np.zeros((3, 5, 2), dtype=np.float64)
>>> x.itemsize
8

So .nbytesis a shortcut for:

所以.nbytes是一个快捷方式:

>>> np.prod(x.shape)*x.itemsize
240
>>> x.nbytes
240

So, to get a base size of a NumPy array without creating an instance of it, you can do this (assuming a 3x5x2 array of doubles for example):

因此,要获得 NumPy 数组的基本大小而不创建它的实例,您可以这样做(例如假设一个 3x5x2 数组):

>>> np.float64(1).itemsize * np.prod([3,5,2])
240

However, important note from the NumPy help file:

但是,NumPy 帮助文件中的重要说明:

|  nbytes
|      Total bytes consumed by the elements of the array.
|
|      Notes
|      -----
|      Does not include memory consumed by non-element attributes of the
|      array object.