gpt4 book ai didi

numpy - numpy.empty() 优于 numpy.ndarray() 的目的是什么?

转载 作者:行者123 更新时间:2023-12-01 13:12:15 29 4
gpt4 key购买 nike

似乎 numpy.empty() 可以做的任何事情都可以使用 numpy.ndarray() 轻松完成,例如:

>>> np.empty(shape=(2, 2), dtype=np.dtype('double'))
array([[ 0., 0.],
[ 0., 0.]])
>>> np.ndarray(shape=(2, 2), dtype=np.dtype('double'))
array([[ 0., 0.],
[ 0., 0.]])
>>>

为什么我们需要 numpy.empty()?它能做一些 numpy.ndarray() 做不到的事情吗?它只是为了向代码阅读者强调您正在创建一个未初始化的数组而起到注释的作用吗?

最佳答案

总是使用np.emptynp.ndarray 是构建数组的低级方法。它由 np.emptynp.array 使用。 np.ndarray 公开了一些您不应该(不小心)自己使用的细节。

来自文档字符串:

Docstring:

ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

For more information, refer to the numpy module and examine the the methods and attributes of an array.

获取文档字符串:

>>> help(np.ndarray)

或者在 IPython 中:

In: [1] np.ndarray?

编辑

正如@hpaulj 在评论中指出的那样,阅读所有相关文档很有用。总是首选 zeros 而不是 empty,除非您有充分的理由不这样做。来自 empty 的文档:

Notes


empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.

关于numpy - numpy.empty() 优于 numpy.ndarray() 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34239822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com