【问题标题】:How are 'numpy.reshape' and 'ndarray.reshape' equivalent?'numpy.reshape' 和 'ndarray.reshape' 如何等效?
【发布时间】:2020-01-15 15:21:57
【问题描述】:

我对@9​​87654321@ 的结构有疑问。我读过numpy.reshape()ndarray.reshape 是python 中用于重塑数组的等效命令。

据我所知,numpy 是一个 Object,其中定义了reshape method。所以numpy.reshape() 中点运算符的使用对我来说是可以理解的。但是说到ndarray.reshape,我不明白点运算符是如何工作的。 ndarray.reshape 中没有对 numpy 对象的引用;它怎么知道reshape和numpy对象相关?

【问题讨论】:

  • numpy.reshape 中,reshapenumpy 模块中的一个函数。在arr.reshape(其中arrnumpy.ndarray)中,reshapendarray 类的方法。从技术上讲,dot 的两种用法都定义了一个命名空间,但函数和方法之间的区别是 Python 的基础。
  • 感谢您提供有用的信息。考虑:b=np.arange(6).reshape(3,2)。因此,在这一行中,np.arange(6) 部分创建了一个对象,该对象被馈送到下一个方法 reshape(3,2)?
  • 是的。 arangenp 模块中的一个函数。reshape 是由 arange 调用创建的对象的方法。结果是一个新的数组对象。分配给b

标签: python numpy reshape


【解决方案1】:

我可能理解错了,但通常numpy 指的是实际的 Numpy 模块,通过调用 numpy.reshape 您正在调用静态函数,您还需要将数组作为第一个参数传递给它,而ndarray 位遵循实际的 numpy 数组。 示例:

# import the module here
import numpy

# create an vector of 9 elements
arr = numpy.random.rand(1,9)

# and now I call the 'static' version of the reshape method:
arr2 = numpy.reshape(arr, (3,3))

# and here I just call the reshape method of the existing array
arr3 = arr.reshape((3,3))

本质上,最后两行代码是等价的,所以arr2arr3 包含相同的3x3 数组。

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2021-03-10
    • 2020-05-10
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多