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(chǎn)’, 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市慢逾,隨后出現(xiàn)的幾起案子灭红,更是在濱河造成了極大的恐慌,老刑警劉巖君珠,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件娇斑,死亡現(xiàn)場離奇詭異,居然都是意外死亡唯竹,警方通過查閱死者的電腦和手機(jī)苦丁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門旺拉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蛾狗,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵撇贺,是天一觀的道長。 經(jīng)常有香客問我松嘶,道長挎扰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任尽超,我火速辦了婚禮梧躺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘巩踏。我一直安慰自己续搀,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布彪杉。 她就那樣靜靜地躺著榛了,像睡著了一般。 火紅的嫁衣襯著肌膚如雪构哺。 梳的紋絲不亂的頭發(fā)上战坤,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天,我揣著相機(jī)與錄音碟嘴,去河邊找鬼囊卜。 笑死错沃,一個(gè)胖子當(dāng)著我的面吹牛雀瓢,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播醒叁,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼泊业,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了饮睬?” 一聲冷哼從身側(cè)響起箱蝠,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎牙瓢,沒想到半個(gè)月后间校,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡胁附,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年控妻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了揭绑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡菇存,死狀恐怖邦蜜,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情悼沈,我是刑警寧澤姐扮,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布溶握,位于F島的核電站蒸播,受9級特大地震影響萍肆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜塘揣,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一亲铡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奖蔓,春花似錦、人聲如沸厨疙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽撒蟀。三九已至温鸽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間配椭,已是汗流浹背雹姊。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留吱雏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓迷守,卻偏偏與公主長得像旺入,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子茵瘾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容