NumPy : Ones and zeros

000. np.empty

numpy.empty(shape, dtype=float, order='C')

Parameters:

shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
order : {‘C’, ‘F’}, optional
Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.
Returns:


out : ndarray
Array of ones with the given shape, dtype, and order.```

read more

  • C-API:
static struct PyMethodDef array_module_methods[] = {
    ...
    {"empty",
        (PyCFunction)array_empty,
        METH_VARARGS|METH_KEYWORDS, NULL},
    ...
}

static PyObject *
array_empty(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds)
{

    static char *kwlist[] = {"shape","dtype","order",NULL};
    PyArray_Descr *typecode = NULL;
    PyArray_Dims shape = {NULL, 0};
    NPY_ORDER order = NPY_CORDER;
    npy_bool is_f_order;
    PyArrayObject *ret = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist,
                PyArray_IntpConverter, &shape,
                PyArray_DescrConverter, &typecode,
                PyArray_OrderConverter, &order)) {
        goto fail;
    }

    switch (order) {
        case NPY_CORDER:
            is_f_order = NPY_FALSE;
            break;
        case NPY_FORTRANORDER:
            is_f_order = NPY_TRUE;
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                            "only 'C' or 'F' order is permitted");
            goto fail;
    }

    ret = (PyArrayObject *)PyArray_Empty(shape.len, shape.ptr,
                                            typecode, is_f_order);

    PyDimMem_FREE(shape.ptr);
    return (PyObject *)ret;

fail:
    Py_XDECREF(typecode);
    PyDimMem_FREE(shape.ptr);
    return NULL;
}

read more

001. np.zeros

numpy.zeros(shape, dtype=float, order='C')

Parameters:

shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
order : {‘C’, ‘F’}, optional
Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.
Returns:


out : ndarray
Array of zeros with the given shape, dtype, and order.


[read more](https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.zeros.html)

- **C-API**

static struct PyMethodDef array_module_methods[] = {
...
{"zeros",
(PyCFunction)array_zeros,
METH_VARARGS|METH_KEYWORDS, NULL},
...
}

static PyObject *
array_zeros(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"shape","dtype","order",NULL};
PyArray_Descr *typecode = NULL;
PyArray_Dims shape = {NULL, 0};
NPY_ORDER order = NPY_CORDER;
npy_bool is_f_order = NPY_FALSE;
PyArrayObject *ret = NULL;

if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist,
            PyArray_IntpConverter, &shape,
            PyArray_DescrConverter, &typecode,
            PyArray_OrderConverter, &order)) {
    goto fail;
}

switch (order) {
    case NPY_CORDER:
        is_f_order = NPY_FALSE;
        break;
    case NPY_FORTRANORDER:
        is_f_order = NPY_TRUE;
        break;
    default:
        PyErr_SetString(PyExc_ValueError,
                        "only 'C' or 'F' order is permitted");
        goto fail;
}

ret = (PyArrayObject *)PyArray_Zeros(shape.len, shape.ptr,
                                    typecode, (int) is_f_order);

PyDimMem_FREE(shape.ptr);
return (PyObject *)ret;

fail:
Py_XDECREF(typecode);
PyDimMem_FREE(shape.ptr);
return (PyObject *)ret;
}


[read more](https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/multiarraymodule.c#L1937-L1977)


##002. np.ones

def ones(shape, dtype=None, order='C'):
a = empty(shape, dtype, order)
multiarray.copyto(a, 1, casting='unsafe')
return a


> 
    Parameters
    ----------
    shape : int or sequence of ints
        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
    dtype : data-type, optional
        The desired data-type for the array, e.g., `numpy.int8`.  Default is
        `numpy.float64`.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    Returns
    -------
    out : ndarray
        Array of ones with the given shape, dtype, and order.

##003. np.empty_like

numpy.empty_like(a, dtype=None, order='K', subok=True)


>```
Parameters:
----------- 
a : array_like
  The shape and data-type of a define these same attributes of the returned array.
dtype : data-type, optional
  Overrides the data type of the result.
order : {‘C’, ‘F’, ‘A’, or ‘K’}, optional
  Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
subok : bool, optional.
  If True, then the newly created array will use the sub-class type of ‘a’, otherwise it will be a base-class array. Defaults to True.
Returns:    
--------
out : ndarray
  Array of uninitialized (arbitrary) data with the same shape and type as a.

read more

  • C-API
static struct PyMethodDef array_module_methods[] = {
  ...
    {"empty_like",
        (PyCFunction)array_empty_like,
        METH_VARARGS|METH_KEYWORDS, NULL},
  ...
}

static PyObject *
array_empty_like(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds)
{

    static char *kwlist[] = {"prototype","dtype","order","subok",NULL};
    PyArrayObject *prototype = NULL;
    PyArray_Descr *dtype = NULL;
    NPY_ORDER order = NPY_KEEPORDER;
    PyArrayObject *ret = NULL;
    int subok = 1;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&i", kwlist,
                &PyArray_Converter, &prototype,
                &PyArray_DescrConverter2, &dtype,
                &PyArray_OrderConverter, &order,
                &subok)) {
        goto fail;
    }
    /* steals the reference to dtype if it's not NULL */
    ret = (PyArrayObject *)PyArray_NewLikeArray(prototype,
                                            order, dtype, subok);
    Py_DECREF(prototype);

    return (PyObject *)ret;

fail:
    Py_XDECREF(prototype);
    Py_XDECREF(dtype);
    return NULL;
}

read more

004 np.zeros_like

def zeros_like(a, dtype=None, order='K', subok=True):
    res = empty_like(a, dtype=dtype, order=order, subok=subok)
    # needed instead of a 0 to get same result as zeros for for string dtypes
    z = zeros(1, dtype=res.dtype)
    multiarray.copyto(res, z, casting='unsafe')
    return res
Parameters
----------
a : array_like
    The shape and data-type of `a` define these same attributes of
    the returned array.
dtype : data-type, optional
    Overrides the data type of the result.
    .. versionadded:: 1.6.0
order : {'C', 'F', 'A', or 'K'}, optional
    Overrides the memory layout of the result. 'C' means C-order,
    'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
    'C' otherwise. 'K' means match the layout of `a` as closely
    as possible.
    .. versionadded:: 1.6.0
subok : bool, optional.
    If True, then the newly created array will use the sub-class
    type of 'a', otherwise it will be a base-class array. Defaults
    to True.
Returns
-------
out : ndarray
    Array of zeros with the same shape and type as `a`.

read more

005. np.ones_like

def ones_like(a, dtype=None, order='K', subok=True):
    res = empty_like(a, dtype=dtype, order=order, subok=subok)
    multiarray.copyto(res, 1, casting='unsafe')
    return res
Parameters
----------
a : array_like
    The shape and data-type of `a` define these same attributes of
    the returned array.
dtype : data-type, optional
    Overrides the data type of the result.
    .. versionadded:: 1.6.0
order : {'C', 'F', 'A', or 'K'}, optional
    Overrides the memory layout of the result. 'C' means C-order,
    'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
    'C' otherwise. 'K' means match the layout of `a` as closely
    as possible.
    .. versionadded:: 1.6.0
subok : bool, optional.
    If True, then the newly created array will use the sub-class
    type of 'a', otherwise it will be a base-class array. Defaults
    to True.
Returns
-------
out : ndarray
    Array of ones with the same shape and type as `a`.

read more

006. np.eye

def eye(N, M=None, k=0, dtype=float):
    if M is None:
        M = N
    m = zeros((N, M), dtype=dtype)
    if k >= M:
        return m
    if k >= 0:
        i = k
    else:
        i = (-k) * M
    m[:M-k].flat[i::M+1] = 1
    return m

Parameters
----------
N : int
  Number of rows in the output.
M : int, optional
  Number of columns in the output. If None, defaults to `N`.
k : int, optional
  Index of the diagonal: 0 (the default) refers to the main diagonal,
  a positive value refers to an upper diagonal, and a negative value
  to a lower diagonal.
dtype : data-type, optional
  Data-type of the returned array.
Returns
-------
I : ndarray of shape (N,M)
  An array where all elements are equal to zero, except for the `k`-th
  diagonal, whose values are equal to one.

read more

007. np.identity

def identity(n, dtype=None):
    from numpy import eye
    return eye(n, dtype=dtype)

Parameters
----------
n : int
    Number of rows (and columns) in `n` x `n` output.
dtype : data-type, optional
    Data-type of the output.  Defaults to ``float``.
Returns
-------
out : ndarray
    `n` x `n` array with its main diagonal set to one,
    and all other elements 0.

read more

008. np.full

def full(shape, fill_value, dtype=None, order='C'):
    if dtype is None:
        dtype = array(fill_value).dtype
    a = empty(shape, dtype, order)
    multiarray.copyto(a, fill_value, casting='unsafe')
    return a

Parameters
----------
shape : int or sequence of ints
    Shape of the new array, e.g., ``(2, 3)`` or ``2``.
fill_value : scalar
    Fill value.
dtype : data-type, optional
    The desired data-type for the array  The default, `None`, means
     `np.array(fill_value).dtype`.
order : {'C', 'F'}, optional
    Whether to store multidimensional data in C- or Fortran-contiguous
    (row- or column-wise) order in memory.
Returns
-------
out : ndarray
    Array of `fill_value` with the given shape, dtype, and order.

read more

009. np.full_like

def full_like(a, fill_value, dtype=None, order='K', subok=True):
    res = empty_like(a, dtype=dtype, order=order, subok=subok)
    multiarray.copyto(res, fill_value, casting='unsafe')
    return res
Parameters
----------
a : array_like
    The shape and data-type of `a` define these same attributes of
    the returned array.
fill_value : scalar
    Fill value.
dtype : data-type, optional
    Overrides the data type of the result.
order : {'C', 'F', 'A', or 'K'}, optional
    Overrides the memory layout of the result. 'C' means C-order,
    'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
    'C' otherwise. 'K' means match the layout of `a` as closely
    as possible.
subok : bool, optional.
    If True, then the newly created array will use the sub-class
    type of 'a', otherwise it will be a base-class array. Defaults
    to True.
Returns
-------
out : ndarray
    Array of `fill_value` with the same shape and type as `a`.

read more

你可能感兴趣的:(NumPy : Ones and zeros)