numpy函數使用筆記

1 numpy.insert

numpy.insert可以有三個參數(arr,obj,values),也可以有4個參數(arr,obj,values,axis):
第一個參數arr是一個數組,可以是一維的也可以是多維的,在arr的基礎上 插入元素
第二個參數obj是元素插入的位置
第三個參數values是需要插入的數值
第四個參數axis是指示在哪一個軸上對應的插入位置進行插入
以下幾點說明:
1)axis=0:從行方向插入
axis=1:從列方向插入
2)如果是多維數據,假如a=[N,C,H,W],N爲行方向,C爲列方向,每次只能插入一列或者一行,無法插入多行或者多列的數組
3)obj是元素插入位置,可以是多個位置插入,待插入值和values中的值對應
官方相關example

Examples
    --------
    >>> a = np.array([[1, 1], [2, 2], [3, 3]])
    >>> a
    array([[1, 1],
           [2, 2],
           [3, 3]])
    >>> np.insert(a, 1, 5)
    array([1, 5, 1, 2, 2, 3, 3])
    >>> np.insert(a, 1, 5, axis=1)
    array([[1, 5, 1],
           [2, 5, 2],
           [3, 5, 3]])
    
    Difference between sequence and scalars:
    
    >>> np.insert(a, [1], [[1],[2],[3]], axis=1)
    array([[1, 1, 1],
           [2, 2, 2],
           [3, 3, 3]])
    >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1),
    ...                np.insert(a, [1], [[1],[2],[3]], axis=1))
    True
    
    >>> b = a.flatten()
    >>> b
    array([1, 1, 2, 2, 3, 3])
    >>> np.insert(b, [2, 2], [5, 6])
    array([1, 1, 5, 6, 2, 2, 3, 3])
    
    >>> np.insert(b, slice(2, 4), [5, 6])
    array([1, 1, 5, 2, 6, 2, 3, 3])
    
    >>> np.insert(b, [2, 2], [7.13, False]) # type casting
    array([1, 1, 7, 0, 2, 2, 3, 3])
    
    >>> x = np.arange(8).reshape(2, 4)
    >>> idx = (1, 3)
    >>> np.insert(x, idx, 999, axis=1)
    array([[  0, 999,   1,   2, 999,   3],
           [  4, 999,   5,   6, 999,   7]])

2 numpy.append

numpu.append(arr,values,axis=None)
功能:將values插入到目標arr的最後。
注意:When axis is specified, values must have the correct shape
Parameters
----------
arr : array_like
Values are appended to a copy of this array.
values : array_like
These values are appended to a copy of arr. It must be of the
correct shape (the same shape as arr, excluding axis). If
axis is not specified, values can be any shape and will be
flattened before use.
axis : int, optional
The axis along which values are appended. If axis is not
given, both arr and values are flattened before use.

axis=0:從行方向插入
axis=1:從列方向插入

3 numpy.delete

delete(arr, obj, axis=None)
功能:返回一個刪除指定軸後的新的數組
Parameters
----------
arr : array_like
Input array.
obj : slice, int or array of ints
Indicate which sub-arrays to remove.
axis : int, optional
The axis along which to delete the subarray defined by obj.
If axis is None, obj is applied to the flattened array.

    Examples
    --------
    >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    >>> arr
    array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12]])
    >>> np.delete(arr, 1, 0)
    array([[ 1,  2,  3,  4],
           [ 9, 10, 11, 12]])
    
    >>> np.delete(arr, np.s_[::2], 1)
    array([[ 2,  4],
           [ 6,  8],
           [10, 12]])
    >>> np.delete(arr, [1,3,5], None)
    array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章