2-14练习题

 

Numpy 练习题

 

打印当前Numpy版本

In [1]:
import numpy as np
In [2]:
print(np.__version__)
 
1.16.4
 

造一个全零矩阵,并打印其占用的内存大小

In [3]:
z=np.zeros((5,5))
print('%d bytes'%(z.size*z.itemsize))
 
200 bytes
 

打印一个函数的帮助文档,比如numpy.add

In [4]:
print(help(np.info(np.add)))
 
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.  If ``x1.shape != x2.shape``, they must be
    broadcastable to a common shape (which may be the shape of one or
    the other).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or `None`,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    Values of True indicate to calculate the ufunc at that position, values
    of False indicate to leave the value in the output alone.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.
    This is a scalar if both `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])
Help on NoneType object:

class NoneType(object)
 |  Methods defined here:
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).

None
 

创建一个10-49的数组,并将其倒序排列

In [5]:
tang_array=np.arange(10,50,1)
tang_array=tang_array[::-1]
tang_array
Out[5]:
array([49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33,
       32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
       15, 14, 13, 12, 11, 10])
 

找到一个数组不为0的索引

In [6]:
np.nonzero([1,2,3,4,5,0,0,0,0,123,22,0,1])
Out[6]:
(array([ 0,  1,  2,  3,  4,  9, 10, 12], dtype=int64),)
 

随机构造一个3*3矩阵,并打印其中最大与最小值

In [7]:
tang_array=np.random.random((3,3))
print(tang_array.min())
print(tang_array.max())
 
0.2830459614587767
0.9498825857162243
 

构造一个5*5的矩阵,令其值都为1,并在最外层加上一圈0

In [8]:
tang_array=np.ones((5,5))
tang_array=np.pad(tang_array,pad_width=1,mode='constant',constant_values=0)#pad是填充,指定填充的层数,模式,值
tang_array
Out[8]:
array([[0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 1., 1., 0.],
       [0., 1., 1., 1., 1., 1., 0.],
       [0., 1., 1., 1., 1., 1., 0.],
       [0., 1., 1., 1., 1., 1., 0.],
       [0., 1., 1., 1., 1., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0.]])
In [9]:
print(help(np.pad))
 
Help on function pad in module numpy:

pad(array, pad_width, mode, **kwargs)
    Pads an array.
    
    Parameters
    ----------
    array : array_like of rank N
        Input array
    pad_width : {sequence, array_like, int}
        Number of values padded to the edges of each axis.
        ((before_1, after_1), ... (before_N, after_N)) unique pad widths
        for each axis.
        ((before, after),) yields same before and after pad for each axis.
        (pad,) or int is a shortcut for before = after = pad width for all
        axes.
    mode : str or function
        One of the following string values or a user supplied function.
    
        'constant'
            Pads with a constant value.
        'edge'
            Pads with the edge values of array.
        'linear_ramp'
            Pads with the linear ramp between end_value and the
            array edge value.
        'maximum'
            Pads with the maximum value of all or part of the
            vector along each axis.
        'mean'
            Pads with the mean value of all or part of the
            vector along each axis.
        'median'
            Pads with the median value of all or part of the
            vector along each axis.
        'minimum'
            Pads with the minimum value of all or part of the
            vector along each axis.
        'reflect'
            Pads with the reflection of the vector mirrored on
            the first and last values of the vector along each
            axis.
        'symmetric'
            Pads with the reflection of the vector mirrored
            along the edge of the array.
        'wrap'
            Pads with the wrap of the vector along the axis.
            The first values are used to pad the end and the
            end values are used to pad the beginning.
        <function>
            Padding function, see Notes.
    stat_length : sequence or int, optional
        Used in 'maximum', 'mean', 'median', and 'minimum'.  Number of
        values at edge of each axis used to calculate the statistic value.
    
        ((before_1, after_1), ... (before_N, after_N)) unique statistic
        lengths for each axis.
    
        ((before, after),) yields same before and after statistic lengths
        for each axis.
    
        (stat_length,) or int is a shortcut for before = after = statistic
        length for all axes.
    
        Default is ``None``, to use the entire axis.
    constant_values : sequence or int, optional
        Used in 'constant'.  The values to set the padded values for each
        axis.
    
        ((before_1, after_1), ... (before_N, after_N)) unique pad constants
        for each axis.
    
        ((before, after),) yields same before and after constants for each
        axis.
    
        (constant,) or int is a shortcut for before = after = constant for
        all axes.
    
        Default is 0.
    end_values : sequence or int, optional
        Used in 'linear_ramp'.  The values used for the ending value of the
        linear_ramp and that will form the edge of the padded array.
    
        ((before_1, after_1), ... (before_N, after_N)) unique end values
        for each axis.
    
        ((before, after),) yields same before and after end values for each
        axis.
    
        (constant,) or int is a shortcut for before = after = end value for
        all axes.
    
        Default is 0.
    reflect_type : {'even', 'odd'}, optional
        Used in 'reflect', and 'symmetric'.  The 'even' style is the
        default with an unaltered reflection around the edge value.  For
        the 'odd' style, the extended part of the array is created by
        subtracting the reflected values from two times the edge value.
    
    Returns
    -------
    pad : ndarray
        Padded array of rank equal to `array` with shape increased
        according to `pad_width`.
    
    Notes
    -----
    .. versionadded:: 1.7.0
    
    For an array with rank greater than 1, some of the padding of later
    axes is calculated from padding of previous axes.  This is easiest to
    think about with a rank 2 array where the corners of the padded array
    are calculated by using padded values from the first axis.
    
    The padding function, if used, should return a rank 1 array equal in
    length to the vector argument with padded values replaced. It has the
    following signature::
    
        padding_func(vector, iaxis_pad_width, iaxis, kwargs)
    
    where
    
        vector : ndarray
            A rank 1 array already padded with zeros.  Padded values are
            vector[:pad_tuple[0]] and vector[-pad_tuple[1]:].
        iaxis_pad_width : tuple
            A 2-tuple of ints, iaxis_pad_width[0] represents the number of
            values padded at the beginning of vector where
            iaxis_pad_width[1] represents the number of values padded at
            the end of vector.
        iaxis : int
            The axis currently being calculated.
        kwargs : dict
            Any keyword arguments the function requires.
    
    Examples
    --------
    >>> a = [1, 2, 3, 4, 5]
    >>> np.pad(a, (2,3), 'constant', constant_values=(4, 6))
    array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])
    
    >>> np.pad(a, (2, 3), 'edge')
    array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5])
    
    >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
    array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])
    
    >>> np.pad(a, (2,), 'maximum')
    array([5, 5, 1, 2, 3, 4, 5, 5, 5])
    
    >>> np.pad(a, (2,), 'mean')
    array([3, 3, 1, 2, 3, 4, 5, 3, 3])
    
    >>> np.pad(a, (2,), 'median')
    array([3, 3, 1, 2, 3, 4, 5, 3, 3])
    
    >>> a = [[1, 2], [3, 4]]
    >>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
    array([[1, 1, 1, 2, 1, 1, 1],
           [1, 1, 1, 2, 1, 1, 1],
           [1, 1, 1, 2, 1, 1, 1],
           [1, 1, 1, 2, 1, 1, 1],
           [3, 3, 3, 4, 3, 3, 3],
           [1, 1, 1, 2, 1, 1, 1],
           [1, 1, 1, 2, 1, 1, 1]])
    
    >>> a = [1, 2, 3, 4, 5]
    >>> np.pad(a, (2, 3), 'reflect')
    array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
    
    >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
    array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])
    
    >>> np.pad(a, (2, 3), 'symmetric')
    array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
    
    >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
    array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
    
    >>> np.pad(a, (2, 3), 'wrap')
    array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
    
    >>> def pad_with(vector, pad_width, iaxis, kwargs):
    ...     pad_value = kwargs.get('padder', 10)
    ...     vector[:pad_width[0]] = pad_value
    ...     vector[-pad_width[1]:] = pad_value
    ...     return vector
    >>> a = np.arange(6)
    >>> a = a.reshape((2, 3))
    >>> np.pad(a, 2, pad_with)
    array([[10, 10, 10, 10, 10, 10, 10],
           [10, 10, 10, 10, 10, 10, 10],
           [10, 10,  0,  1,  2, 10, 10],
           [10, 10,  3,  4,  5, 10, 10],
           [10, 10, 10, 10, 10, 10, 10],
           [10, 10, 10, 10, 10, 10, 10]])
    >>> np.pad(a, 2, pad_with, padder=100)
    array([[100, 100, 100, 100, 100, 100, 100],
           [100, 100, 100, 100, 100, 100, 100],
           [100, 100,   0,   1,   2, 100, 100],
           [100, 100,   3,   4,   5, 100, 100],
           [100, 100, 100, 100, 100, 100, 100],
           [100, 100, 100, 100, 100, 100, 100]])

None
 

构建一个shape为(6,7,8)的矩阵,并找到第100个元素的索引值

In [10]:
np.unravel_index(100,(6,7,8))
Out[10]:
(1, 5, 4)
 

对一个5*5的矩阵做归一化操作

In [11]:
tang_array=np.random.random((5,5))
tang_max=tang_array.max()
tang_min=tang_array.min()
tang_array=(tang_array-tang_min)/(tang_max-tang_min)
tang_array
Out[11]:
array([[0.81910099, 0.5732582 , 0.05873658, 0.69382984, 0.        ],
       [0.39419867, 0.3164082 , 0.98168918, 0.11459765, 0.65324366],
       [0.40928635, 0.63326605, 0.86588683, 0.77114142, 0.09296318],
       [0.7088501 , 1.        , 0.51195   , 0.19436486, 0.94982958],
       [0.24767082, 0.9946443 , 0.24577929, 0.67141774, 0.11190727]])
 

找到两个数组中相同的值

In [12]:
A=np.random.randint(0,10,10)
B=np.random.randint(0,10,10)
print(A)
print(B)
print(np.intersect1d(A,B))
 
[5 3 8 3 8 4 0 5 3 9]
[8 4 0 7 6 7 2 6 9 5]
[0 4 5 8 9]
 

得到今天 昨天 明天 的日期

In [13]:
yesterday=np.datetime64('today','D')-np.timedelta64(1,'D')
today=np.datetime64('today','D')
tomorrow=np.datetime64('today','D')+np.timedelta64(1,'D')
print(today)
print(tomorrow)
print(yesterday)
 
2019-09-26
2019-09-27
2019-09-25
 

得到一个月中所有的天

In [14]:
np.arange('2017-10','2017-11',dtype='datetime64[D]')
Out[14]:
array(['2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04',
       '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08',
       '2017-10-09', '2017-10-10', '2017-10-11', '2017-10-12',
       '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16',
       '2017-10-17', '2017-10-18', '2017-10-19', '2017-10-20',
       '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-24',
       '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28',
       '2017-10-29', '2017-10-30', '2017-10-31'], dtype='datetime64[D]')
 

得到一个数的整数部分

In [15]:
z=np.random.uniform(0,10,10)
np.floor(z)#得到整数部分
Out[15]:
array([6., 6., 5., 8., 8., 1., 2., 9., 5., 6.])
 

构造一个数组,让它不能被改变

In [16]:
z=np.zeros(5)
z.flags.writeable=Flalse#z只可以读不可以写
z[0]=1
 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-d04551baedf4> in <module>()
      1 z=np.zeros(5)
----> 2z.flags.writeable=Flalse#z只可以读不可以写
      3 z[0]=1

NameError: name 'Flalse' is not defined
 

打印大数据的部分值,全部值

In [17]:
np.set_printoptions(threshold=5)#限制阀值为5,
z=np.zeros((15,15))
z
Out[17]:
array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]])
In [18]:
np.set_printoptions(threshold=10000)#打印全:threshold这个参数需要设置成一个很大的数不然会报错
z=np.zeros((15,15))
z
Out[18]:
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
 

找到在一个数组中最接近一个数的索引

In [19]:
z=np.arange(100)
v=np.random.uniform(0,100)
print(v)
index=(np.abs(z-v)).argmin()#广播功能
print(z[index])
 
25.080309716074968
25
 

32位float类型和32位int类型转换

In [20]:
z=np.arange(10,dtype=np.int32)
print(z.dtype)
z=z.astype(np.float32)
print(z.dtype)
 
int32
float32
 

打印数组元素的位置坐标和数值

In [21]:
z=np.arange(9).reshape(3,3)
for index,value in np.ndenumerate(z):
     print(index,value)
 
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8
 

按照数组的某一列进行排列

In [22]:
z=np.random.randint(0,10,(3,3))
print(z)
print(z[z[:,1].argsort()])#1:代表第二列,按照第二列排序
 
[[7 5 5]
 [7 8 1]
 [0 4 5]]
[[0 4 5]
 [7 5 5]
 [7 8 1]]
 

统计数组中每个数值出现的次数

In [23]:
z=np.array([1,1,1,2,2,3,3,3,4,5,8])
np.bincount(z)#0:有0个 1:有3个 2:有3个……8:有1个
Out[23]:
array([0, 3, 2, 3, 1, 1, 0, 0, 1], dtype=int64)
 

如何对一个四位数组最后两维来求和

In [24]:
z=np.random.randint(0,10,(4,4,4,4))#4维数组
res=z.sum(axis=(-2,-1))#后两维
res
Out[24]:
array([[74, 55, 71, 53],
       [70, 78, 95, 91],
       [91, 89, 47, 84],
       [71, 87, 65, 81]])
 

交换矩阵中的两行

In [25]:
z=np.random.randint(0,25,(5,5))
z[[1,0]]=z[[0,1]]#交换行数
z
Out[25]:
array([[17, 16,  9, 15, 17],
       [15, 10, 12,  3,  6],
       [16, 14, 10,  2, 15],
       [21, 12, 14,  3, 14],
       [14, 13, 23, 24,  0]])
 

找到数组里最常出现的数字

In [26]:
z=np.random.randint(0,10,50)
print(np.bincount(z).argmax())#argmax():在计数后,值最大所对应位置的具体值
 
8
 

快速查找TOP k

In [27]:
z=np.arange(10000)
np.random.shuffle(z)#洗牌
n=5
print(z[np.argpartition(-z,n)[:n]])#np.argpartition(-z,n):找最大的z=》-z   找多少个 :n   [:n]:取前n个
 
[9997 9999 9998 9996 9995]
 

去掉一个数组中,所有元素都相同的数组

In [28]:
np.set_printoptions(threshold=10000)#打印全:threshold这个参数需要设置成一个很大的数
z=np.random.randint(0,5,(10,3))
z
Out[28]:
array([[0, 1, 2],
       [2, 2, 0],
       [2, 2, 2],
       [2, 1, 0],
       [1, 4, 0],
       [0, 2, 4],
       [0, 1, 0],
       [4, 1, 3],
       [1, 4, 1],
       [0, 3, 3]])
In [29]:
e=np.all(z[:,1:]==z[:,:-1],axis=1)
print(e)
 
[False False  True False False False False False False False]
In [42]:
A=np.where(e==1)[0]
B=np.delete(z,2,axis=0)#delete,z不会变,要重新赋一个变量
z

#Z=z[~e]
#Z
Out[42]:
array([[0, 1, 2],
       [2, 2, 0],
       [2, 1, 0],
       [1, 4, 0],
       [0, 2, 4],
       [0, 1, 0],
       [4, 1, 3],
       [1, 4, 1],
       [0, 3, 3]])
In [31]:
a=np.array([1,2,3,4])
b=np.array([1,2,3,5])
np.all(a==b)#判断所有的是否一样
Out[31]:
False
In [ ]:
np.any(a==b)#判断任何是否一样

猜你喜欢

转载自www.cnblogs.com/AI-robort/p/11627194.html