python - numpy: "array_like"对象的正式定义?

标签 python numpy

在 numpy 中,许多对象的构造函数接受“array_like”作为第一个参数。是否有这样的对象的定义,或者作为抽象元类,或者方法的文档应该包含??

最佳答案

事实证明,从技术上讲,几乎所有东西都是类似数组的。 “类数组”更像是对如何解释输入的陈述,而不是对输入内容的限制;如果参数被记录为类数组,NumPy 将尝试将其解释为数组。

除了the nearly tautological one 之外,没有关于类数组的正式定义。 -- 类数组是 np.array 可以转换为 ndarray 的任何 Python 对象。要超越这一点,您需要研究 source code .

NPY_NO_EXPORT PyObject *
PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
                int max_depth, int flags, PyObject *context)
{
    /*
     * This is the main code to make a NumPy array from a Python
     * Object.  It is called from many different places.
     */
    PyArrayObject *arr = NULL, *ret;
    PyArray_Descr *dtype = NULL;
    int ndim = 0;
    npy_intp dims[NPY_MAXDIMS];

    /* Get either the array or its parameters if it isn't an array */
    if (PyArray_GetArrayParamsFromObject(op, newtype,
                        0, &dtype,
                        &ndim, dims, &arr, context) < 0) {
        Py_XDECREF(newtype);
        return NULL;
    }
    ...

特别有趣的是PyArray_GetArrayParamsFromObject ,其注释列举了 np.array 期望的对象类型:

NPY_NO_EXPORT int
PyArray_GetArrayParamsFromObject(PyObject *op,
                        PyArray_Descr *requested_dtype,
                        npy_bool writeable,
                        PyArray_Descr **out_dtype,
                        int *out_ndim, npy_intp *out_dims,
                        PyArrayObject **out_arr, PyObject *context)
{
    PyObject *tmp;

    /* If op is an array */

    /* If op is a NumPy scalar */

    /* If op is a Python scalar */

    /* If op supports the PEP 3118 buffer interface */

    /* If op supports the __array_struct__ or __array_interface__ interface */

    /*
     * If op supplies the __array__ function.
     * The documentation says this should produce a copy, so
     * we skip this method if writeable is true, because the intent
     * of writeable is to modify the operand.
     * XXX: If the implementation is wrong, and/or if actual
     *      usage requires this behave differently,
     *      this should be changed!
     */

    /* Try to treat op as a list of lists */

    /* Anything can be viewed as an object, unless it needs to be writeable */

}

所以通过研究源代码我们可以得出一个类似数组的is

关于python - numpy: "array_like"对象的正式定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378427/

相关文章:

python - 如何在生产数据库上运行 django 单元测试?

python - 将位串 numpy 数组转换为整数基数 2 的最快方法

numpy - 特征分解让我对 numpy 感到好奇

python - 在 tox.ini 中指定 hg 依赖项

python - 如何使用strided_slice选择tensorflow中的所有元素?

python - CEF Python 代理身份验证

python - 为什么 numpy.corrcoef() 返回 nan?

python - NumPy 中的 np.dot 打印预期内容的转置

python - 使用 Python/NumPy 对图像阈值进行矢量化

python - 并行安装 Python 2.7.1 和 Apple 提供的 Python