Numpy基础练习100题[前50题]

Numpy基础练习100题

项目来源:https://github.com/rougier/numpy-100

1.导入numpy库并取名字为np

import numpy as np

2.打印输出numpy的版本和配置信息

np.__version__
'1.18.5'
np.show_config()
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]

3. 创建一个长度为10的空向量

np.zeros(10)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

4.如何找到任何一个数组的内存大小

Z = np.zeros((10,10)) # 10*10为的矩阵
print(Z)
print("%d bytes" % (Z.size * Z.itemsize))
[[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.]]
800 bytes

5. 如何从命令行得到numpy中add函数的说明文档?

np.info(np.add) # 查看numpy工具包下的函数使用方法,很好用
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 becomes the shape of the output).
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
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``, locations within it where the condition is False will
    remain uninitialized.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs `.

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.]])

6. 创建一个长度为10并且除了第五个值为1的空向量

Z = np.zeros(10)
Z[4] = 11
print(Z)
[ 0.  0.  0.  0. 11.  0.  0.  0.  0.  0.]

7. 创建一个值域范围从10到49的向量

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

8. 反转一个向量(第一个元素变为最后一个)

Z = np.arange(50)
print(Z)
# 反转
Z = Z[ : :-1]
print(Z)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 48 49]
[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  9  8  7  6  5  4  3  2
  1  0]

9.创建一个 3x3 并且值从0到8的矩阵

Z = np.arange(9).reshape(3,3)
Z
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

10. 找到数组[1,2,0,0,4,0]中非0元素的位置索引

nz = np.nonzero([1,2,0,0,4,0])
nz
(array([0, 1, 4], dtype=int64),)

11. 创建一个 3x3 的单位矩阵

Z = np.eye(3)
Z
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

12. 创建一个 3x3x3的随机数组

Z = np.random.randint((3,3,3))
print(Z)
Z = np.random.random((3,3,3))
print(Z)
[0 1 0]
[[[0.11703768 0.15665001 0.98059487]
  [0.6993327  0.12187568 0.3595888 ]
  [0.00963102 0.2946496  0.21467848]]

 [[0.96731389 0.98007911 0.18310304]
  [0.09436081 0.52595679 0.14685079]
  [0.38102119 0.28924822 0.59280225]]

 [[0.02146097 0.79842838 0.91450769]
  [0.65038213 0.78833875 0.85063171]
  [0.24328237 0.53458248 0.67568819]]]

13. 创建一个 10x10 的随机数组并找到它的最大值和最小值

Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
0.010219243058963379 0.9890317300014234

14. 创建一个长度为30的随机向量并找到它的平均值

Z = np.random.random(30)
m = Z.mean()
print(m)
0.5125907170974495

15. 创建一个二维数组,其中边界值为1,其余值为0

Z = np.ones((10,10))
Z[1:-1,1:-1] = 0 # 这里怎么理解?
# 1到-1表示行列的位置,比如(1,1)(1,2)....(1,9),到第三行(2,1),(2,2)....(2,9),依次下去
print(Z)
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

16. 对于一个存在在数组,如何添加一个用0填充的边界?

Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
[[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.]]

看一看np.pad的用法
np.pad()常用与深度学习中的数据预处理,可以将numpy数组按指定的方法填充成指定的形状。

方法参数:pad(array, pad_width, mode, **kwargs)
array:表示需要填充的数组;
pad_width:表示每个轴(axis)边缘需要填充的数值数目;
mode:表示填充的方式(取值:str字符串或用户提供的函数)

mode中的填充方式:
constant’——表示连续填充相同的值,每个轴可以分别指定填充值,constant_values=(x, y)
时前面用x填充,后面用y填充,缺省值填充0

17. 下面表达式运行的结果是什么?

 0 * np.nan
nan
np.nan == np.nan # 这里返回F,可以这样理解,无穷!=无穷
False
np.inf > np.nan
False
np.nan - np.nan
nan
0.3 == 3*0.1 #3*0.1=0.30000000000000004
False

18.创建一个 5x5的矩阵,并设置值1,2,3,4落在其对角线下方位置

Z = np.diag(1+np.arange(4),k=-1)
print(Z)
[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]
np.info(np.diag)
 diag(*args, **kwargs)

Extract a diagonal or construct a diagonal array.

See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.

Parameters
----------
v : array_like
    If `v` is a 2-D array, return a copy of its `k`-th diagonal.
    If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
    diagonal.
k : int, optional
    Diagonal in question. The default is 0. Use `k>0` for diagonals
    above the main diagonal, and `k<0` for diagonals below the main
    diagonal.

Returns
-------
out : ndarray
    The extracted diagonal or constructed diagonal array.

See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.

Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])

>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

19. 创建一个8x8 的矩阵,并且设置成棋盘样式

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
#Z[i:j:s] 
# 请参考https://blog.csdn.net/mingyuli/article/details/81604795的解释,我的理解是i和j大致是行列,s的话表示步长,当s<0时,Z[::-1]=a[-1:-len(a)-1:-1]
np.info(Z)
class:  ndarray
shape:  (5, 5)
strides:  (20, 4)
itemsize:  4
aligned:  True
contiguous:  True
fortran:  False
data pointer: 0x1b9eaedb1f0
byteorder:  little
byteswap:  False
type: int32

20. 考虑一个 (6,7,8) 形状的数组,其第100个元素的索引(x,y,z)是什么?

print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)

21. 用tile函数去创建一个 8x8的棋盘样式矩阵

Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]
np.tile()的用法 https://blog.csdn.net/qq_18433441/article/details/54897250

22. 对一个5x5的随机矩阵做归一化

Z = np.random.random((5,5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)
[[0.92042311 0.26179001 0.60885399 0.5080942  0.8458998 ]
 [0.80656232 1.         0.52691876 0.64033586 0.23159865]
 [0.71899013 0.61207932 0.01697865 0.55172094 0.28752424]
 [0.99494883 0.02310809 0.71209696 0.80976307 0.        ]
 [0.51834008 0.95287447 0.18104636 0.93275269 0.8524711 ]]

23. 创建一个将颜色描述为(RGBA)四个无符号字节的自定义dtype?

color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
color
C:\Users\kingS\anaconda3\lib\site-packages\ipykernel_launcher.py:4: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  after removing the cwd from sys.path.





dtype([('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')])

24.一个5x3的矩阵与一个3x2的矩阵相乘,实矩阵乘积是什么?

Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]

25. 给定一个一维数组,对其在3到8之间的所有元素取反

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

26. 下面脚本运行后的结果是什么?

print(sum(range(5),-1))                  
9
print(sum(range(5),-1))   
10

27. 考虑一个整数向量Z,下列表达合法的是哪个?

Z = np.arange(1,3)
Z
array([1, 2])
Z**Z
array([1, 4], dtype=int32)
2 << Z >> 2
array([1, 2], dtype=int32)
Z <- Z
array([False, False])
1j*Z
array([0.+1.j, 0.+2.j])
Z / 1/1
array([1., 2.])
Z < Z > Z
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
----> 1 Z < Z > Z


ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

28. 下面表达式的结果分别是什么?

np.array(0) / np.array(0)   
C:\Users\kingS\anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
  """Entry point for launching an IPython kernel.





nan

np.array(0) // np.array(0)                      
C:\Users\kingS\anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in floor_divide
  """Entry point for launching an IPython kernel.





0

np.array([np.nan]).astype(int).astype(float)        -2.14748365e+09
array([-4.2949673e+09])

29. 如何从零位开始舍入浮点数组?

Z = np.random.uniform(-10,+10,10)
print (np.copysign(np.ceil(np.abs(Z)), Z))
[ 1.  6.  9. -8.  5. -3. -2.  8. 10.  1.]

30. 如何找出两个数组公共的元素?

Z1 = np.random.randint(0, 10, 10)
Z2 = np.random.randint(0, 10, 10)
print (np.intersect1d(Z1, Z2))
[0 3 5 6 7]
np.random.uniform(-10,+10,10)
array([ 2.24073511, -4.68397267,  1.51454992, -8.12404611,  5.70720372,
        4.69355634,  5.93706946, -0.68425276,  4.40537982,  5.29810174])
np.ceil(np.random.uniform(-10,+10,10))
array([-5., -3.,  1.,  2., -8., -7.,  7., -6., -1., -0.])

31. 如何忽略所有的 numpy 警告(尽管不建议这么做)?

# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# Back to sanity
_ = np.seterr(**defaults)

# 另一个等价的方式, 使用上下文管理器(context manager)
with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0
Z
array([inf])

32. 下面的表达式是否为真?

np.sqrt(-1) == np.emath.sqrt(-1)
C:\Users\kingS\anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
  """Entry point for launching an IPython kernel.





False

33. 如何获得昨天,今天和明天的日期?

yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
tomorrow
numpy.datetime64('2021-06-04')
np.datetime64('today', 'D')
numpy.datetime64('2021-06-03')

34. 怎么获得所有与2016年7月的所有日期?

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

35. 如何计算 ((A+B)*(-A/2)) (不使用中间变量)?

A = np.ones(3) * 1
B = np.ones(3) * 1
C = np.ones(3) * 1
np.add(A, B, out=B)
np.divide(A, 2, out=A)
np.negative(A, out=A)
np.multiply(A, B, out=A)
array([-1., -1., -1.])

36. 用5种不同的方法提取随机数组中的整数部分

Z = np.random.uniform(0, 10, 10)
print(Z)
print (Z - Z % 1) # 
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
[6.80650555 1.74342436 2.70167401 0.73914672 0.94154516 7.27902873
 8.63727446 8.81343166 8.8309756  7.5328844 ]
[6. 1. 2. 0. 0. 7. 8. 8. 8. 7.]
[6. 1. 2. 0. 0. 7. 8. 8. 8. 7.]
[6. 1. 2. 0. 0. 7. 8. 8. 8. 7.]
[6 1 2 0 0 7 8 8 8 7]
[6. 1. 2. 0. 0. 7. 8. 8. 8. 7.]
1.2 % 1
0.19999999999999996

37. 创建一个5x5的矩阵且每一行的值范围为从0到4

Z = np.zeros((5, 5))
Z += np.arange(5)
print (Z)
[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

38. 如何用一个生成10个整数的函数来构建数组

def generate():
    for x in range(10):
      yield x
Z = np.fromiter(generate(), dtype=float, count=-1)
print (Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
np.fromiter用法和解释 https://blog.csdn.net/MaeveShi/article/details/107388473

39. 创建一个大小为10的向量, 值域为0到1,不包括0和1

Z = np.linspace(0, 1, 12, endpoint=True)[1: -1]
print (Z)
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]
np.linspace(0, 1, 12, endpoint=True)
array([0.        , 0.08333333, 0.16666667, 0.25      , 0.33333333,
       0.41666667, 0.5       , 0.58333333, 0.66666667, 0.75      ,
       0.83333333, 0.91666667])
np.info(np.linspace)
 linspace(*args, **kwargs)

Return evenly spaced numbers over a specified interval.

Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].

The endpoint of the interval can optionally be excluded.

.. versionchanged:: 1.16.0
    Non-scalar `start` and `stop` are now supported.

Parameters
----------
start : array_like
    The starting value of the sequence.
stop : array_like
    The end value of the sequence, unless `endpoint` is set to False.
    In that case, the sequence consists of all but the last of ``num + 1``
    evenly spaced samples, so that `stop` is excluded.  Note that the step
    size changes when `endpoint` is False.
num : int, optional
    Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
    If True, `stop` is the last sample. Otherwise, it is not included.
    Default is True.
retstep : bool, optional
    If True, return (`samples`, `step`), where `step` is the spacing
    between samples.
dtype : dtype, optional
    The type of the output array.  If `dtype` is not given, infer the data
    type from the other input arguments.

    .. versionadded:: 1.9.0

axis : int, optional
    The axis in the result to store the samples.  Relevant only if start
    or stop are array-like.  By default (0), the samples will be along a
    new axis inserted at the beginning. Use -1 to get an axis at the end.

    .. versionadded:: 1.16.0

Returns
-------
samples : ndarray
    There are `num` equally spaced samples in the closed interval
    ``[start, stop]`` or the half-open interval ``[start, stop)``
    (depending on whether `endpoint` is True or False).
step : float, optional
    Only returned if `retstep` is True

    Size of spacing between samples.


See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
         number of samples).
geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
            scale (a geometric progression).
logspace : Similar to `geomspace`, but with the end points specified as
           logarithms.

Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([2.  , 2.25, 2.5 , 2.75, 3.  ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. ,  2.2,  2.4,  2.6,  2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

Graphical illustration:

>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[]
>>> plt.plot(x2, y + 0.5, 'o')
[]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()

40. 创建一个大小为10的随机向量,并把它排序

Z = np.random.random(10)
Z.sort()
print (Z)
[0.10705316 0.11344548 0.45293034 0.45776226 0.5286275  0.54259117
 0.56924058 0.69027986 0.7160883  0.7170026 ]

41. 对一个小数组进行求和有没有办法比np.sum更快?

Z = np.arange(10)
np.add.reduce(Z) # rdcuce感觉像是累(加、减、乘)

45
np.info(np.add.reduce)
reduce(a, axis=0, dtype=None, out=None, keepdims=False, initial=, where=True)

Reduces `a`'s dimension by one, by applying ufunc along one axis.

Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`.  Then
:math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
For a one-dimensional array, reduce produces results equivalent to:
::

 r = op.identity # op = ufunc
 for i in range(len(A)):
   r = op(r, A[i])
 return r

For example, add.reduce() is equivalent to sum().

Parameters
----------
a : array_like
    The array to act on.
axis : None or int or tuple of ints, optional
    Axis or axes along which a reduction is performed.
    The default (`axis` = 0) is perform a reduction over the first
    dimension of the input array. `axis` may be negative, in
    which case it counts from the last to the first axis.

    .. versionadded:: 1.7.0

    If this is None, a reduction is performed over all the axes.
    If this is a tuple of ints, a reduction is performed on multiple
    axes, instead of a single axis or all the axes as before.

    For operations which are either not commutative or not associative,
    doing a reduction over multiple axes is not well-defined. The
    ufuncs do not currently raise an exception in this case, but will
    likely do so in the future.
dtype : data-type code, optional
    The type used to represent the intermediate results. Defaults
    to the data-type of the output array if this is provided, or
    the data-type of the input array if no output array is provided.
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If not provided or None,
    a freshly-allocated array is returned. For consistency with
    ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
    1-element tuple.

    .. versionchanged:: 1.13.0
       Tuples are allowed for keyword argument.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

    .. versionadded:: 1.7.0
initial : scalar, optional
    The value with which to start the reduction.
    If the ufunc has no identity or the dtype is object, this defaults
    to None - otherwise it defaults to ufunc.identity.
    If ``None`` is given, the first element of the reduction is used,
    and an error is thrown if the reduction is empty.

    .. versionadded:: 1.15.0

where : array_like of bool, optional
    A boolean array which is broadcasted to match the dimensions
    of `a`, and selects elements to include in the reduction. Note
    that for ufuncs like ``minimum`` that do not have an identity
    defined, one has to pass in also ``initial``.

    .. versionadded:: 1.17.0

Returns
-------
r : ndarray
    The reduced array. If `out` was supplied, `r` is a reference to it.

Examples
--------
>>> np.multiply.reduce([2,3,5])
30

A multi-dimensional array example:

>>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> np.add.reduce(X, 0)
array([[ 4,  6],
       [ 8, 10]])
>>> np.add.reduce(X) # confirm: default axis value is 0
array([[ 4,  6],
       [ 8, 10]])
>>> np.add.reduce(X, 1)
array([[ 2,  4],
       [10, 12]])
>>> np.add.reduce(X, 2)
array([[ 1,  5],
       [ 9, 13]])

You can use the ``initial`` keyword argument to initialize the reduction
with a different value, and ``where`` to select specific elements to include:

>>> np.add.reduce([10], initial=5)
15
>>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
array([14., 14.])
>>> a = np.array([10., np.nan, 10])
>>> np.add.reduce(a, where=~np.isnan(a))
20.0

Allows reductions of empty arrays where they would normally fail, i.e.
for ufuncs without an identity.

>>> np.minimum.reduce([], initial=np.inf)
inf
>>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
array([ 1., 10.])
>>> np.minimum.reduce([])
Traceback (most recent call last):
    ...
ValueError: zero-size array to reduction operation minimum which has no identity

42. 如何判断两和随机数组相等

A = np.random.randint(0, 2, 5)
B = np.random.randint(0, 2, 5)

# 假设array的形状(shape)相同和一个误差容限(tolerance)
equal = np.allclose(A,B)
print(equal)

# 检查形状和元素值,没有误差容限(值必须完全相等)
equal = np.array_equal(A,B)
print(equal)
False
False

43. 把数组变为只读

Z = np.zeros(5)
Z.flags.writeable = True # 改成False会报错
Z[0] = 1
Z
array([1., 0., 0., 0., 0.])

44. 将一个10x2的笛卡尔坐标矩阵转换为极坐标

Z = np.random.random((10, 2))
X, Y = Z[:, 0], Z[:, 1]
R = np.sqrt(X**2 + Y**2)
T = np.arctan2(Y, X)
print (R)
print (T)
[0.99476243 0.18120069 0.24878277 0.35681154 1.02005226 0.79621116
 1.06348455 1.25476229 0.75381007 0.76924139]
[0.83628677 1.31222218 1.18569439 0.28174263 0.36789134 0.0800995
 1.16991472 0.71520923 0.83252375 1.04955151]
np.random.random((10, 2))
array([[0.54801274, 0.22043258],
       [0.14532328, 0.96551325],
       [0.24424964, 0.99437072],
       [0.79961282, 0.94123918],
       [0.43329684, 0.79543283],
       [0.73901185, 0.44119212],
       [0.6425194 , 0.47897277],
       [0.66040064, 0.41569665],
       [0.92180864, 0.78082399],
       [0.72624301, 0.21686495]])

45. 创建一个大小为10的随机向量并且将该向量中最大的值替换为0

Z = np.random.random(10)
Z[Z.argmax()] = 0
print (Z)
[0.0027154  0.11186707 0.73458462 0.85812928 0.         0.13017252
 0.68314185 0.32608012 0.90231489 0.39966661]
Z = np.random.random(10)
Z.argmax()# 返回第几个最大
1
Z.max()
0.9270562760783981

46. 创建一个结构化数组,其中x和y坐标覆盖[0, 1]x[1, 0]区域

Z = np.zeros((5, 5), [('x', float), ('y', float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5))
print (Z)
[[(0.  , 0.  ) (0.25, 0.  ) (0.5 , 0.  ) (0.75, 0.  ) (1.  , 0.  )]
 [(0.  , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1.  , 0.25)]
 [(0.  , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1.  , 0.5 )]
 [(0.  , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1.  , 0.75)]
 [(0.  , 1.  ) (0.25, 1.  ) (0.5 , 1.  ) (0.75, 1.  ) (1.  , 1.  )]]

47. 给定两个数组X和Y,构造柯西(Cauchy)矩阵C

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YFILBw7c-1622651660496)(attachment:image.png)]

X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print (C)
print(np.linalg.det(C)) # 计算行列式
[[-2.         -0.66666667 -0.4        -0.28571429 -0.22222222 -0.18181818
  -0.15384615 -0.13333333]
 [ 2.         -2.         -0.66666667 -0.4        -0.28571429 -0.22222222
  -0.18181818 -0.15384615]
 [ 0.66666667  2.         -2.         -0.66666667 -0.4        -0.28571429
  -0.22222222 -0.18181818]
 [ 0.4         0.66666667  2.         -2.         -0.66666667 -0.4
  -0.28571429 -0.22222222]
 [ 0.28571429  0.4         0.66666667  2.         -2.         -0.66666667
  -0.4        -0.28571429]
 [ 0.22222222  0.28571429  0.4         0.66666667  2.         -2.
  -0.66666667 -0.4       ]
 [ 0.18181818  0.22222222  0.28571429  0.4         0.66666667  2.
  -2.         -0.66666667]
 [ 0.15384615  0.18181818  0.22222222  0.28571429  0.4         0.66666667
   2.         -2.        ]]
3638.163637117973
# 这点好像是没看懂,涉及到数学了

48. 打印每个numpy 类型的最小和最大可表示值

for dtype in [np.int8, np.int32, np.int64]:
   print(np.iinfo(dtype).min)
   print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
   print(np.finfo(dtype).min)
   print(np.finfo(dtype).max)
   print(np.finfo(dtype).eps)
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.4028235e+38
3.4028235e+38
1.1920929e-07
-1.7976931348623157e+308
1.7976931348623157e+308
2.220446049250313e-16

49. 如何打印数组中所有的值?

np.set_printoptions(threshold=10000)# np.nan替换10000会报错
Z = np.zeros((16,16))
print(Z)
[[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. 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.]]

50. 如何在数组中找到与给定标量接近的值?

Z = np.arange(100)
v = np.random.uniform(0, 100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
# 结果:18

你可能感兴趣的:(python基础,python,numpy)