100道练习带你玩转Numpy(附答案)

1.导入numpy库并简写为 np (★☆☆)

  • (提示: import … as …)
import numpy as np

参考答案

import numpy as np

2. 打印numpy的版本和配置说明 (★☆☆)

  • (提示: np.version, np.show_config)
#查看numpy的版本
np.__version__

输出结果

'1.21.1'
#查看numpyd的配置说明:注意np.show_config与np.show_config()区别
print(np.show_config)
print("________________________")
print(np.show_config())

输出结果

<function show at 0x000001B6BFC9DAF0>
________________________
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
Supported SIMD extensions in this NumPy install:
    baseline = SSE,SSE2,SSE3
    found = SSSE3,SSE41,POPCNT,SSE42,AVX,F16C,FMA3,AVX2
    not found = AVX512F,AVX512CD,AVX512_SKX,AVX512_CLX,AVX512_CNL
None

参考答案

print(np.__version__)
print(np.show_config())

输出结果

1.21.1
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_info']
    libraries = ['openblas_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    library_dirs = ['D:\\a\\1\\s\\numpy\\build\\openblas_lapack_info']
    libraries = ['openblas_lapack_info']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
Supported SIMD extensions in this NumPy install:
    baseline = SSE,SSE2,SSE3
    found = SSSE3,SSE41,POPCNT,SSE42,AVX,F16C,FMA3,AVX2
    not found = AVX512F,AVX512CD,AVX512_SKX,AVX512_CLX,AVX512_CNL
None

3. 创建一个长度为10的空向量 (★☆☆)

  • (提示: np.zeros)
a = np.zeros(10)
a

输出结果

array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

参考答案

Z = np.zeros(10)
print(Z)

输出结果

[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

4. 如何找到任何一个数组的内存大小? (★☆☆)

  • (提示: size, itemsize)
print(a.size,a.itemsize)

输出结果

10 8

参考答案

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))

输出结果

800 bytes

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

  • (提示: np.info)
np.info(toplevel='add')

参考答案

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

The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0.,  2.,  4.],
       [ 3.,  5.,  7.],
       [ 6.,  8., 10.]])

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

  • (提示: array[4])
array6 = np.zeros(10)
array6[4] = 1
array6

输出结果

array([0., 0., 0., 0., 1., 0., 0., 0., 0., 0.])

参考答案

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

输出结果

[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

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

  • (提示: np.arange)
array7 = np.arange(10,50)
array7

输出结果

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

参考答案

Z = np.arange(10,50)
print(Z)

输出结果

[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. 反转一个向量(第一个元素变为最后一个) (★☆☆)

  • (提示: array[::-1])
#一维数组情况
array8 = np.arange(10)
print(array8,"\n-----\n",type(array8),"\n-----\n",array8[::-1],"\n-----\n")

print("注意以下区别:")
print("只取向量最后一个元素:\n",array8[-1])
print("------------")
print("取向量第一个元素到倒数第二个:\n",array8[:-1])
print("------------")
print("反转向量:\n",array8[::-1])

输出结果

[0 1 2 3 4 5 6 7 8 9] 
-----
 <class 'numpy.ndarray'> 
-----
 [9 8 7 6 5 4 3 2 1 0] 
-----

注意以下区别:
只取向量最后一个元素:
 9
------------
取向量第一个元素到倒数第二个:
 [0 1 2 3 4 5 6 7 8]
------------
反转向量:
 [9 8 7 6 5 4 3 2 1 0]
#二维数组情况
array8 = np.arange(12).reshape(3,4)
print(array8,"\n-----\n",type(array8),"\n-----\n",array8[::-1],"\n-----\n")

print("注意以下区别:")
print("只取数组最后一行元素:\n",array8[-1])
print("------------")
print("注意与上一个不同:\n",array8[-1::])
print("------------")
print("取数组第一行元素到倒数第二行:\n",array8[:-1])
print("------------")
print("同上一个:\n",array8[:-1:])
print("------------")
print("数组最后一行到第一行,以此类推:\n",array8[::-1])

输出结果

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]] 
-----
 <class 'numpy.ndarray'> 
-----
 [[ 8  9 10 11]
 [ 4  5  6  7]
 [ 0  1  2  3]] 
-----

注意以下区别:
只取数组最后一行元素:
 [ 8  9 10 11]
------------
注意与上一个不同:
 [[ 8  9 10 11]]
------------
取数组第一行元素到倒数第二行:
 [[0 1 2 3]
 [4 5 6 7]]
------------
同上一个:
 [[0 1 2 3]
 [4 5 6 7]]
------------
数组最后一行到第一行,以此类推:
 [[ 8  9 10 11]
 [ 4  5  6  7]
 [ 0  1  2  3]]

参考答案

Z = np.arange(50)
Z = Z[::-1]
print(Z)

输出结果

[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的矩阵(★☆☆)

  • (提示: reshape)
array9 = np.arange(0,9).reshape(3,3)
array9

输出结果

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

参考答案

Z = np.arange(9).reshape(3,3)
print(Z)

输出结果

[[0 1 2]
 [3 4 5]
 [6 7 8]]

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

  • (提示: np.nonzero)
array10 = [1,2,0,0,4,0]
np.nonzero(array10)

输出结果

(array([0, 1, 4], dtype=int64),)

参考答案

nz = np.nonzero([1,2,0,0,4,0])
print(nz)

输出结果

(array([0, 1, 4], dtype=int64),)

11. 创建一个 3x3 的单位矩阵 (★☆☆)

  • (提示: np.eye)
array11 = np.eye(3,3)
array11

输出结果

array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

参考答案

Z = np.eye(3)
print(Z)

输出结果

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

12. 创建一个 3x3x3的随机数组 (★☆☆)

  • (提示: np.random.random)
array12 = np.random.random(27).reshape(3,3,3)
array12

输出结果

array([[[0.82229851, 0.97063002, 0.14368023],
        [0.54370589, 0.03199196, 0.85705309],
        [0.26821559, 0.15694076, 0.51977488]],

       [[0.50242734, 0.29862912, 0.95963966],
        [0.4059865 , 0.58694668, 0.82554167],
        [0.56819152, 0.34225528, 0.45214493]],

       [[0.01517539, 0.89008166, 0.0500397 ],
        [0.03236231, 0.19130355, 0.53311733],
        [0.09538655, 0.18586758, 0.58278421]]])

参考答案

Z = np.random.random((3,3,3))
print(Z)

输出结果

[[[0.28037142 0.44488439 0.30333044]
  [0.1161553  0.82102038 0.25739631]
  [0.09821049 0.36713993 0.92724096]]

 [[0.2454338  0.87448758 0.50827198]
  [0.54874904 0.07023286 0.75978993]
  [0.98004792 0.42379336 0.98222663]]

 [[0.43035063 0.32212228 0.22881998]
  [0.97116268 0.10329178 0.19237496]
  [0.89617807 0.79191292 0.51751459]]]

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

  • (提示: min, max)
array13 = np.random.random(100).reshape(10,10)

print(array13,"\n最大值为\n",array13.max(),"\n最小值为:\n",array13.min())

输出结果

[[0.99778825 0.58095976 0.34966491 0.61488926 0.22311257 0.4618689
  0.17235173 0.70900466 0.98204539 0.16713024]
 [0.47931749 0.37411923 0.174987   0.4546529  0.18531676 0.75502785
  0.13397944 0.45530322 0.43508141 0.95361024]
 [0.17900297 0.93651411 0.87413906 0.73874406 0.52680645 0.64828029
  0.24795946 0.88003906 0.62365578 0.80426776]
 [0.45185357 0.51363758 0.96072332 0.04641699 0.48586224 0.62842817
  0.27009438 0.18875272 0.19874009 0.66220609]
 [0.44138034 0.2363918  0.74719564 0.22923504 0.27315476 0.53374481
  0.18482755 0.50381315 0.25225246 0.75322919]
 [0.35705613 0.51395832 0.51189048 0.09275676 0.75417333 0.06750219
  0.43249999 0.62178538 0.46245924 0.65893803]
 [0.27734846 0.24961469 0.44867329 0.96181551 0.69065328 0.21640466
  0.59641193 0.12161551 0.54862819 0.67923836]
 [0.21021391 0.32386752 0.37686985 0.85766783 0.73454876 0.69567777
  0.79764775 0.28465536 0.4209324  0.35587512]
 [0.15687547 0.69758606 0.3013893  0.53512701 0.99620145 0.22607022
  0.11752308 0.54600039 0.9315894  0.63885842]
 [0.95544494 0.55211529 0.96081971 0.92697433 0.44943367 0.52602786
  0.64950368 0.40008766 0.59628704 0.09932262]] 
最大值为
 0.9977882475176502 
最小值为:
 0.046416985065966254

参考答案

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

输出结果

0.004121552994131639 0.9861579216981144

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

  • (提示: mean)
array14 = np.random.random(30)
print(array14,"\n-------\n",array14.mean())

输出结果

[0.93012289 0.87846182 0.39524015 0.29766567 0.535985   0.96190709
 0.11612866 0.49828173 0.41661926 0.3161008  0.45526546 0.45677439
 0.42808616 0.2136142  0.85161725 0.72934575 0.88087434 0.17033377
 0.71800939 0.74070516 0.25254667 0.15898121 0.25780968 0.65958564
 0.10230427 0.94045116 0.80328989 0.6013053  0.66213565 0.50255439] 
-------
 0.5310700936558221

参考答案

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

输出结果

0.3515583279019299

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

  • (提示: array[1:-1, 1:-1])
array15 = np.ones(9).reshape(3,3)
print(array15,"\n------\n")
array15[1:-1, 1:-1] = 0
print(array15)

输出结果

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]] 
------

[[1. 1. 1.]
 [1. 0. 1.]
 [1. 1. 1.]]

参考答案

Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
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填充的边界? (★☆☆)

  • (提示: np.pad)
  • np.pad用法详解
  • np.pad(array, pad_width, mode=‘constant’, **kwargs)
    • array:数组
    • pad_width
    • mode
      • constant
      • edge
      • linear_ramp
      • maximum
      • mean
      • median
      • reflect
      • symmetric
      • wrap
    • **kwargs
#用常量填充
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]]
print(a)
np.pad(a, ((3, 2), (2, 3)), 'minimum')

输出结果

[[1, 2], [3, 4]]
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
    
a = np.arange(6)
a = a.reshape((2, 3))
np.pad(a, 1, pad_with)

输出结果

array([[10, 10, 10, 10, 10],
       [10,  0,  1,  2, 10],
       [10,  3,  4,  5, 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]])
array16 = np.arange(1,7)
array16 = array16.reshape(2, 3)
print(array16)
np.pad(array16, ((1, 1),(1,1)), 'constant', constant_values=(0, 0))

输出结果

[[1 2 3]
 [4 5 6]]
array([[0, 0, 0, 0, 0],
       [0, 1, 2, 3, 0],
       [0, 4, 5, 6, 0],
       [0, 0, 0, 0, 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.]]

17. 以下表达式运行的结果分别是什么? (★☆☆)

  • (提示: NaN = not a number, inf = infinity)
  • 0 * np.nan
  • np.nan == np.nan
  • np.inf > np.nan
  • np.nan - np.nan
  • 0.3 == 3 * 0.1

参考答案

#0 * np.nan:nan
print("0 * np.nan输出为:",0 * np.nan)

#np.nan == np.nan:False
print("np.nan == np.nan输出为:",np.nan == np.nan)


#np.inf > np.nan:False
print("np.inf > np.nan输出为:",np.inf > np.nan)

#np.nan - np.nan:nan
print("np.nan - np.nan输出为:",np.nan - np.nan)


#0.3 == 3 * 0.1:False
print("0.3 == 3 * 0.1输出为:",0.3 == 3 * 0.1)

输出结果

0 * np.nan输出为: nan
np.nan == np.nan输出为: False
np.inf > np.nan输出为: False
np.nan - np.nan输出为: nan
0.3 == 3 * 0.1输出为: False

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

  • (提示: np.diag)

参考答案

#参考答案
#np.diag(v, k=0)
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]]

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

  • (提示: array[::2])
array19 = np.ones((8,8))
array19[1::2,::2]= 0
array19[::2,1::2]= 0
array19

输出结果

array([[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.],
       [0., 1., 0., 1., 0., 1., 0., 1.]])

参考答案

#参考答案
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]]

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

  • (提示: np.unravel_index)

参考答案

#参考答案
#unravel_index(indices, shape, order='C')
print(np.unravel_index(100,(6,7,8)))

输出结果

(1, 5, 4)

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

  • (提示: np.tile)
  • np.tile(A, reps)相关用法
#一维数组情况
a = np.array([0, 1, 2])
print(np.tile(a, 2))
print("-----------")
print(np.tile(a, (2, 2)))
print("-----------")
print(np.tile(a, (2, 2, 2)))

输出结果

[0 1 2 0 1 2]
-----------
[[0 1 2 0 1 2]
 [0 1 2 0 1 2]]
-----------
[[[0 1 2 0 1 2]
  [0 1 2 0 1 2]]

 [[0 1 2 0 1 2]
  [0 1 2 0 1 2]]]
c = np.array([1,2,3,4])
print(np.tile(c,(4,1)))
print("-----------")
print(np.tile(c,(1,4)))

输出结果

[[1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]]
-----------
[[1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4]]
#二维数组
b = np.array([[1, 2], [3, 4]])
print(np.tile(b, 2))
print("-----------")
print(np.tile(b, (2, 1)))

输出结果

[[1 2 1 2]
 [3 4 3 4]]
-----------
[[1 2]
 [3 4]
 [1 2]
 [3 4]]
array21 = np.array([[0,1],[1,0]])
print(array21)
print("-------------")
print(np.tile(array21, (4,4)))

输出结果

[[0 1]
 [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]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

参考答案

#参考答案
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]]

22. 对一个5x5的随机矩阵做归一化(★☆☆)

  • (提示: (x - min) / (max - min))
array22 = np.random.random(25).reshape(5,5)
amin = array22.min()
amax = array22.max()
print(array22,"\n最小值为:\n",amin,"\n最大值为:\n",amax)

array_new = (array22 - amin)/(amax - amin)
array_new

输出结果

[[0.26009871 0.89989705 0.79188441 0.70944836 0.24024913]
 [0.13928614 0.97029819 0.07942416 0.20779984 0.7193373 ]
 [0.14027008 0.45981306 0.31472733 0.70832382 0.65386747]
 [0.57767974 0.37985315 0.8988651  0.80697825 0.74939784]
 [0.46605384 0.95553957 0.92271522 0.22827105 0.44096403]] 
最小值为:
 0.0794241626441996 
最大值为:
 0.9702981944156541
array([[0.20280594, 0.92097519, 0.79973175, 0.70719784, 0.18052493],
       [0.06719466, 1.        , 0.        , 0.14410082, 0.71829811],
       [0.06829912, 0.42698393, 0.2641262 , 0.70593556, 0.64480868],
       [0.55928848, 0.33722948, 0.91981684, 0.81667448, 0.75204086],
       [0.43398917, 0.98343354, 0.94658844, 0.16707961, 0.40582602]])

参考答案

#参考答案
Z = np.random.random((5,5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)

输出结果

[[0.12258481 0.48605201 0.72046827 0.68510051 0.77727713]
 [1.         0.62709158 0.30209518 0.88260495 0.        ]
 [0.85075924 0.53774393 0.45084072 0.60056524 0.38530611]
 [0.18323325 0.93486688 0.93560248 0.63488952 0.3298871 ]
 [0.82238802 0.35623848 0.9348605  0.4193811  0.47054688]]

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

  • (提示: np.dtype)

参考答案

#参考答案
#np.dtype(self, /, *args, **kwargs)
color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
color

输出结果

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

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

  • (提示: np.dot | @)
array241 = np.random.randint(0,10,(5,3))
array242 = np.random.randint(0,10,(3,2))

print(array241,type(array241),"\n----\n",array242,type(array242))
print("-----------")

array24 = np.dot(array241,array242)
print(array24)

输出结果

[[7 9 8]
 [9 5 1]
 [8 8 9]
 [1 4 6]
 [1 7 4]] <class 'numpy.ndarray'> 
----
 [[7 0]
 [0 4]
 [0 1]] <class 'numpy.ndarray'>
-----------
[[49 44]
 [63 21]
 [56 41]
 [ 7 22]
 [ 7 32]]
from numpy import *
from numpy.linalg import *

array241 = matrix(np.random.randint(0,10,(5,3)))
array242 = matrix(np.random.randint(0,10,(3,2)))

print(array241,type(array241),"\n----\n",array242,type(array242))
print("-----------")

array24 = np.dot(array241,array242)
print(array24)

输出结果

[[1 5 8]
 [3 1 6]
 [0 4 1]
 [9 4 3]
 [6 3 8]] <class 'numpy.matrix'> 
----
 [[4 5]
 [0 7]
 [6 4]] <class 'numpy.matrix'>
-----------
[[52 72]
 [48 46]
 [ 6 32]
 [54 85]
 [72 83]]

参考答案

#参考答案
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之间的所有元素取反 (★☆☆)

  • (提示: >, <=)
array25 = np.array([1,2,3,4,5,6,7,8,9,0])
array25[(array25>=3) & (array25 <= 8)] *= -1
array25

输出结果

array([ 1,  2, -3, -4, -5, -6, -7, -8,  9,  0])

参考答案

#参考答案
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)

输出结果

[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

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

  • (提示: np.sum)
  • print(sum(range(5),-1))
  • from numpy import *
  • print(sum(range(5),-1))

参考答案

#参考答案

#求和
print(sum(range(5),-1))  

#导入numpy模块
from numpy import *  

#求和
print(sum(range(5),-1))

输出结果

10
10

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

  • Z**Z
  • 2 << Z >> 2
  • Z <- Z
  • 1j*Z
  • Z/1/1
  • ZZ
Z = np.array([1,2,3,4])
print(Z**Z)

输出结果

[  1   4  27 256]
print(2 << Z >> 2)

输出结果

[1 2 4 8]
print(Z <- Z)

输出结果

[False False False False]
print(1j*Z)

输出结果

[0.+1.j 0.+2.j 0.+3.j 0.+4.j]
print(Z/1/1)

输出结果

array([1., 2., 3., 4.])
#不合法
#ZZ

参考答案

#参考答案
Z = np.arange(5)
Z ** Z  # legal

输出结果

array([  1,   1,   4,  27, 256], dtype=int32)
Z = np.arange(5)
2 << Z >> 2  # false

输出结果

array([0, 1, 2, 4, 8], dtype=int32)
Z = np.arange(5)
Z <- Z   # legal

输出结果

array([False, False, False, False, False])
Z = np.arange(5)
1j*Z   # legal

输出结果

array([0.+0.j, 0.+1.j, 0.+2.j, 0.+3.j, 0.+4.j])
Z = np.arange(5)
Z/1/1   # legal

输出结果

array([0., 1., 2., 3., 4.])
Z = np.arange(5)
#ZZ    # false

28. 下列表达式的结果分别是什么?(★☆☆)

  • np.array(0) / np.array(0)
  • np.array(0) // np.array(0)
  • np.array([np.nan]).astype(int).astype(float)

参考答案

#参考答案
np.array(0) / np.array(0)

输出结果

nan
np.array(0) // np.array(0)

输出结果

0
np.array([np.nan]).astype(int).astype(float)

输出结果

array([-2.14748365e+09])

29. 如何从零位对浮点数组做舍入 ? (★☆☆)

  • (提示: np.uniform, np.copysign, np.ceil, np.abs)
#补充知识:np.copysign()
print(np.copysign(1.3, -1))
print("-----------")
print(1/np.copysign(0, 1))
print("-----------")
print(1/np.copysign(0, -1))
print("-----------")
print(np.copysign([-1, 0, 1], -1.1))
print("-----------")
print(np.copysign([-1, 0, 1], np.arange(3)-1))

输出结果

-1.3
-----------
inf
-----------
-inf
-----------
[-1. -0. -1.]
-----------
[-1.  0.  1.]
#补充知识:np.ceil()
a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
np.ceil(a)

输出结果

array([-1., -1., -0.,  1.,  2.,  2.,  2.])
#补充知识:np.abs()
x = np.array([-1.2, 1.2])
print(abs(x))

x = np.array([-1.2, 1.2])
print(np.absolute(x))
print(np.absolute(1.2 + 1j))

输出结果

[1.2 1.2]
[1.2 1.2]
1.5620499351813308
import matplotlib.pyplot as plt

x = np.linspace(start=-10, stop=10, num=101)
plt.plot(x, np.absolute(x))
plt.show()

xx = x + 1j * x[:, np.newaxis]
plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
plt.show()
array29 = np.random.random(5)
print(array29,type(array29))
print("-----------")
print(np.ceil(array29))

输出结果

[0.38875538 0.57606542 0.97401344 0.61982858 0.79914594] <class 'numpy.ndarray'>
-----------
[1. 1. 1. 1. 1.]

参考答案

Z = np.random.uniform(-10,+10,10)
print(Z)
print("-----------")
print(np.copysign(np.ceil(np.abs(Z)), Z))

输出结果

[-9.67597981 -0.36041212  6.07506503 -0.86278789 -5.98091448  6.4237606
  1.43246588  3.03546255 -8.31970362  1.94764631]
-----------
[-10.  -1.   7.  -1.  -6.   7.   2.   4.  -9.   2.]

30. 如何找到两个数组中的共同元素? (★☆☆)

  • (提示: np.intersect1d)
  • np.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)用法
np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])

输出结果

array([1, 3])
from functools import reduce
reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))

输出结果

array([3])
x = np.array([1, 1, 2, 3, 4])
y = np.array([2, 1, 4, 6])
xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
xy,x_ind, y_ind

输出结果

(array([1, 2, 4]),
 array([0, 2, 4], dtype=int64),
 array([1, 0, 2], dtype=int64))
xy, x[x_ind], y[y_ind]

输出结果

(array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
arr1 = np.array([1,2,3,4])
arr2 = np.array([4,5,6,7])
np.intersect1d(arr1,arr2)

输出结果

array([4])

参考答案

#参考答案
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(Z1,"\n-------\n",Z2,"\n-------")
print(np.intersect1d(Z1,Z2))

输出结果

[6 6 9 8 1 0 1 0 9 1] 
-------
 [1 2 3 2 2 2 0 9 9 2] 
-------
[0 1 9]

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

  • (提示: np.seterr, np.errstate)
  • np.seterr(all=None, divide=None, over=None, under=None, invalid=None)
  • np.errstate(*,call=,**kwargs,)

参考答案

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

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

#An equivalent way, with a context manager:  

with np.errstate(divide='ignore'):  
    Z = np.ones(1) / 0

32. 下面的表达式是正确的吗? (★☆☆)

  • (提示: imaginary number)
  • np.sqrt(-1) == np.emath.sqrt(-1)

参考答案

np.sqrt(-1) == np.emath.sqrt(-1)

输出结果

False

33. 如何得到昨天,今天,明天的日期? (★☆☆)

  • (提示: np.datetime64, np.timedelta64)
#np.datetime64(self, /, *args, **kwargs)

print(np.datetime64(10, 'Y'))
print(np.datetime64(10, 'D'))

输出结果

1980
1970-01-11
#np.timedelta64(self, /, *args, **kwargs)
np.timedelta64(10)

输出结果

numpy.timedelta64(10)

参考答案

#参考答案
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print ("Yesterday is " + str(yesterday))
print ("Today is " + str(today))
print ("Tomorrow is "+ str(tomorrow))

输出结果

Yesterday is 2021-08-24
Today is 2021-08-25
Tomorrow is 2021-08-26

34. 如何得到所有与2016年7月对应的日期? (★★☆)

  • (提示: np.arange(dtype=datetime64[‘D’]))

参考答案

#参考答案
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)(不建立副本)? (★★☆)

  • (提示: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=))

参考答案

A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
print(A,B,C)
print("-----------")
print(np.add(A,B,out=B))
print("-----------")
print(A,B,C)

输出结果

[1. 1. 1.] [2. 2. 2.] [3. 3. 3.]
-----------
[3. 3. 3.]
-----------
[1. 1. 1.] [3. 3. 3.] [3. 3. 3.]
print(np.divide(A,2,out=A))
print("-----------")
print(A,B,C)

输出结果

[0.5 0.5 0.5]
-----------
[0.5 0.5 0.5] [3. 3. 3.] [3. 3. 3.]
print(np.negative(A,out=A))
print("-----------")
print(A,B,C)

输出结果

[-0.5 -0.5 -0.5]
-----------
[-0.5 -0.5 -0.5] [3. 3. 3.] [3. 3. 3.]
print(np.multiply(A,B,out=A))
print("-----------")
print(A,B,C)

输出结果

[-1.5 -1.5 -1.5]
-----------
[-1.5 -1.5 -1.5] [3. 3. 3.] [3. 3. 3.]

36. 用五种不同的方法去提取一个随机数组的整数部分(★★☆)

  • (提示: %, np.floor, np.ceil, astype, np.trunc)
array36 = np.random.uniform(-10,+10,10)
print(array36)

输出结果

[ 6.16472162 -1.05905698  2.13578326 -3.65313804  7.49143151 -4.99765465
 -8.27078759  2.35452296  9.55808418 -1.5001378 ]
array36_1 = array36 - array36%1
array36_1

输出结果

array([ 6., -2.,  2., -4.,  7., -5., -9.,  2.,  9., -2.])
array36_2 = np.floor(array36)
array36_2

输出结果

array([ 6., -2.,  2., -4.,  7., -5., -9.,  2.,  9., -2.])
array36_3 = np.ceil(array36)
array36_3

输出结果

array([ 7., -1.,  3., -3.,  8., -4., -8.,  3., 10., -1.])
#a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
array36_4 = array36.astype(int)
array36_4

输出结果

array([ 6, -1,  2, -3,  7, -4, -8,  2,  9, -1])
array36_5 = np.trunc(array36)
array36_5

输出结果

array([ 6., -1.,  2., -3.,  7., -4., -8.,  2.,  9., -1.])

参考答案

#参考答案
Z = np.random.uniform(0,10,10)

print (Z - Z%1)

输出结果

[2. 8. 9. 9. 5. 8. 4. 7. 0. 6.]
print (np.floor(Z))

输出结果

[2. 8. 9. 9. 5. 8. 4. 7. 0. 6.]
print (np.ceil(Z)-1)

输出结果

[2. 8. 9. 9. 5. 8. 4. 7. 0. 6.]
print (Z.astype(int))

输出结果

[2 8 9 9 5 8 4 7 0 6]
print (np.trunc(Z))

输出结果

[2. 8. 9. 9. 5. 8. 4. 7. 0. 6.]

37. 创建一个5x5的矩阵,其中每行的数值范围从0到4 (★★☆)

  • (提示: np.arange)

参考答案

#参考答案
Z = np.zeros((5,5))
print(Z)
print("---------")
Z += np.arange(5)
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. 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个整数的函数,来构建一个数组(★☆☆)

  • (提示: np.fromiter)
iterable = (x for x in np.random.randint(0,100,10))
np.fromiter(iterable, int)

输出结果

array([65, 92, 67, 31, 35, 54, 40, 14, 48, 46])
iterable = (x for x in range(10))
np.fromiter(iterable, int)

输出结果

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

参考答案

#参考答案
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.]

39. 创建一个长度为10的随机向量,其值域范围从0到1,但是不包括0和1 (★★☆)

  • (提示: np.linspace)
array39 = np.linspace(0,1,num=11,endpoint= False)[1:]
array39

输出结果

array([0.09090909, 0.18181818, 0.27272727, 0.36363636, 0.45454545,
       0.54545455, 0.63636364, 0.72727273, 0.81818182, 0.90909091])

参考答案

#参考答案
Z = np.linspace(0,1,11,endpoint=False)[1:]
print (Z)

输出结果

[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]

40. 创建一个长度为10的随机向量,并将其排序 (★★☆)

  • (提示: sort)
array40 = np.random.randint(0,100,10)
print("array40向量为:\n",array40,"\n------------")
print("array40排序为:\n",np.sort(array40, axis=-1),"\n------------")
print("array40向量没有发生改变:\n",array40,"\n------------")

array40.sort()
print("array40向量发生改变:\n",array40)

输出结果

array40向量为:
 [55  1 31 87 28 55 85 37 71 84] 
------------
array40排序为:
 [ 1 28 31 37 55 55 71 84 85 87] 
------------
array40向量没有发生改变:
 [55  1 31 87 28 55 85 37 71 84] 
------------
array40向量发生改变:
 [ 1 28 31 37 55 55 71 84 85 87]

参考答案

Z = np.random.random(10)
Z.sort()
print(Z)

输出结果

[0.01108845 0.05596719 0.26378488 0.32935733 0.42652857 0.56806563
 0.61323955 0.90232693 0.94617123 0.99070713]

41.对于一个小数组,如何用比 np.sum更快的方式对其求和?(★★☆)

  • (提示: np.add.reduce)
array41 = np.random.randint(0,100,20).reshape(4,5)
print(array41,"\n------------")
print("np.sum求和:",np.sum(array41,axis = 0))
print("np.add.reduce求和:",np.add.reduce(array41))

输出结果

[[56 89  2 35 41]
 [68 30 51 15 61]
 [72 50 69 49 96]
 [14 27 48 89 69]] 
------------
np.sum求和: [210 196 170 188 267]
array([210, 196, 170, 188, 267])

参考答案

#参考答案
Z = np.arange(10)
np.add.reduce(Z)

输出结果

45

42. 对于两个随机数组A和B,检查它们是否相等(★★☆)

  • (提示: np.allclose, np.array_equal)
#np.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
print(np.allclose([1e10,1e-7], [1.00001e10,1e-8]))
print(np.allclose([1e10,1e-8], [1.00001e10,1e-9]))
print(np.allclose([1e10,1e-8], [1.0001e10,1e-9]))
print(np.allclose([1.0, np.nan], [1.0, np.nan]))
print(np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True))

输出结果

False
True
False
False
True
#np.array_equal(a1, a2, equal_nan=False)
print(np.array_equal([1, 2], [1, 2]))
print(np.array_equal(np.array([1, 2]), np.array([1, 2])))
print(np.array_equal([1, 2], [1, 2, 3]))
print(np.array_equal([1, 2], [1, 4]))

a = np.array([1, np.nan])
print(np.array_equal(a, a))
print(np.array_equal(a, a, equal_nan=True))

a = np.array([1 + 1j])
b = a.copy()
a.real = np.nan
b.imag = np.nan
print(np.array_equal(a, b, equal_nan=True))

输出结果

True
True
False
False
False
True
True
A = np.random.randint(0,100,5)
B = np.random.randint(0,100,5)
print(A,"\n------------\n",B,"\n------------")
print("A与B是否相等:",np.allclose(A,B))
print("A与B是否相等:",np.array_equal(A,B))

输出结果

[68 75 89 50 24] 
------------
 [35 76  1 59 90] 
------------
A与B是否相等: False
A与B是否相等: False

参考答案

#参考答案
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)

输出结果

True
# 方法2
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)

输出结果

True

43. 创建一个只读数组(read-only) (★★☆)

  • (提示: flags.writeable)
#参考答案
Z = np.zeros(10)  
Z.flags.writeable = False  
Z[0] = 1 

44. 将笛卡尔坐标下的一个10x2的矩阵转换为极坐标形式(★★☆)

  • (hint: np.sqrt, np.arctan2)

参考答案

#参考答案
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.92221092 1.03210565 1.1226919  1.07363888 0.91806222 0.44833899
 0.92030651 0.0995045  0.48589723 0.75119929]
[0.69468262 1.11817969 0.75553459 0.96033932 0.61850187 0.87891577
 1.49597306 0.7527101  1.39087811 1.52194917]

45. 创建一个长度为10的向量,并将向量中最大值替换为1 (★★☆)

  • (提示: argmax)
array45 = np.random.randint(0,100,10)
print("array45向量为:\n",array45)
array45[array45.argmax()] = 1
print("更改后为:\n",array45)

输出结果

array45向量为:
 [96 21 61 33 38 77 72 49 59 54]
更改后为:
 [ 1 21 61 33 38 77 72 49 59 54]

参考答案

Z = np.random.random(10)
Z[Z.argmax()] = 1
print (Z)

输出结果

[0.85538406 0.08771085 0.56525424 0.38459612 0.16379397 0.90891447
 1.         0.12933557 0.84031549 0.31512573]

46. 创建一个结构化数组,并实现 x 和 y 坐标覆盖 [0,1]x[0,1] 区域 (★★☆)

  • (提示: np.meshgrid)
#np.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
nx, ny = (3, 2)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
xv, yv = np.meshgrid(x, y)
print(xv)
print(yv)

xv, yv = np.meshgrid(x, y, sparse=True)  # make sparse output arrays
print(xv)
print(yv)

输出结果

[[0.  0.5 1. ]
 [0.  0.5 1. ]]
[[0. 0. 0.]
 [1. 1. 1.]]
[[0.  0.5 1. ]]
[[0.]
 [1.]]
#`meshgrid` is very useful to evaluate functions on a grid.
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
plt.show()

参考答案

#参考答案
Z = np.zeros((5,5), [('x',float),('y',float)])
print(Z,"\n----------")
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
                             np.linspace(0,1,5))
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.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 (Cij =1/(xi - yj))

  • (提示: np.subtract.outer)

参考答案

#参考答案
X = np.arange(8)
print(X,"\n----------")
Y = X + 0.5
print(Y,"\n----------")
C = 1.0 / np.subtract.outer(X, Y)
print(C,"\n----------")
print(np.linalg.det(C))

输出结果

[0 1 2 3 4 5 6 7] 
----------
[0.5 1.5 2.5 3.5 4.5 5.5 6.5 7.5] 
----------
[[-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.1636371179666

48. 打印每个numpy标量类型的最小值和最大值? (★★☆)

  • (提示: np.iinfo, np.finfo, eps)
#np.iinfo(int_type)
ii16 = np.iinfo(np.int16)
print(ii16.min,"\n----------\n",ii16.max)

输出结果

-32768 
----------
 32767
ii32 = np.iinfo(np.int32)
print(ii32.min,"\n----------\n",ii32.max)

输出结果

-2147483648 
----------
 2147483647
ii32 = np.iinfo(np.int32(10))
print(ii32.min,"\n----------\n",ii32.max)

输出结果

-2147483648 
----------
 2147483647
#np.finfo(dtype)

参考答案

#参考答案
for dtype in [np.int8, np.int32, np.int64]:
    print(np.iinfo(dtype).min,"\n----------")
    print(np.iinfo(dtype).max,"\n----------")

for dtype in [np.float32, np.float64]:
    print(np.finfo(dtype).min,"\n----------")
    print(np.finfo(dtype).max,"\n----------")
    print(np.finfo(dtype).eps,"\n----------")

输出结果

-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)
#np.set_printoptions(precision=None,threshold=None,edgeitems=None,linewidth=None,
#suppress=None,nanstr=None,infstr=None,formatter=None,sign=None,floatmode=None,*,legacy=None,)
#控制输出的小数点个数是4
np.set_printoptions(precision=4)
np.array([1.123456789])

输出结果

array([1.1235])
#Long arrays can be summarised:
#控制输出的值的个数为6,其余以...代替
np.set_printoptions(threshold=5)
np.arange(10)

输出结果

array([0, 1, 2, ..., 7, 8, 9])

参考答案

#控制台输出所有的值,不需要省略号
#但是会报错,后续发现是这个方法应该是没有的
np.set_printoptions(threshold=np.nan) 
np.arange(10)
  • Python3使用np.set_printoptions(threshold=np.nan)引发错误解决方法
    • 目的是把阀值调到足够大,能够显示任意长度的数组,因此只需要借助sys模块就可以实现
import numpy as np
import sys
np.set_printoptions(threshold=6) 
Z = np.zeros((16,16))
print(Z) 

# 修改阀值 
np.set_printoptions(threshold=sys.maxsize) 
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. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
  • precision : int, 可选,float输出的精度,即小数点后维数,默认8。
  • threshold : int, 可选,当数组数目过大时,设置显示几个数字,其余用省略号。
  • edgeitems : int, 可选,边缘数目,每个维度开始和结束时摘要中的数组项数,默认3
  • linewidth : int, 可选,用于确定每行多少字符数后插入换行符,默认为75。
  • suppress : bool, 可选,是否压缩由科学计数法表示的浮点数,默认False。
  • nanstr : str, 可选,浮点非数字的字符串表示形式,默认nan
  • infstr : str, 可选,浮点无穷大的字符串表示形式,默认inf
#Small results can be suppressed:

eps = np.finfo(float).eps
x = np.arange(4.)
x**2 - (x + eps)**2

输出结果

array([-4.9304e-32, -4.4409e-16,  0.0000e+00,  0.0000e+00])
np.set_printoptions(suppress=True)
x**2 - (x + eps)**2

输出结果

array([-0., -0.,  0.,  0.])
#A custom formatter can be used to display array elements as desired:

np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
x = np.arange(3)
x

输出结果

array([int: 0, int: -1, int: -2])
# formatter gets reset
np.set_printoptions()  
x

输出结果

array([0, 1, 2])
#To put back the default options, you can use:
np.set_printoptions(edgeitems=3, infstr='inf',linewidth=75, nanstr='nan', precision=8,suppress=False, threshold=1000, formatter=None)

#Also to temporarily override options, use `printoptions` as a context manager:

with np.printoptions(precision=2, suppress=True, threshold=5):
     np.linspace(0, 10, 10)

50. 给定标量时,如何找到数组中最接近标量的值?(★★☆)

  • (提示: argmin)
#np.argmin(a, axis=None, out=None):返回的是最小值的索引
a = np.arange(6).reshape(2,3) + 10
print(a,"\n----------\n",np.argmin(a))

输出结果

[[10 11 12]
 [13 14 15]] 
----------
 0
np.argmin(a, axis=0)

输出结果

array([0, 0, 0], dtype=int64)
np.argmin(a, axis=1)

输出结果

array([0, 0], dtype=int64)
#Indices of the minimum elements of a N-dimensional array:

ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
ind

输出结果

(0, 0)
#返回的是最小值
a[ind]

输出结果

10
b = np.arange(6) + 10
b[4] = 10
b

输出结果

array([10, 11, 12, 13, 10, 15])
# Only the first occurrence is returned.
#多个最小值存在时只会
np.argmin(b)  

输出结果

0
x = np.array([[4,2,3], [1,0,3]])
index_array = np.argmin(x, axis=-1)
# Same as np.min(x, axis=-1, keepdims=True)
np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)

输出结果

array([[2],
       [0]])
# Same as np.max(x, axis=-1)
np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)

输出结果

array([2, 0])

参考答案

#参考答案
Z = np.arange(100)
print(Z,"\n------")
v = np.random.uniform(0,100)
print(v,"\n------")
index = (np.abs(Z-v)).argmin()
print (Z[index])

输出结果

[ 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 96 97 98 99] 
------
59.4391273262911 
------
59

51. 创建一个表示位置(x,y)和颜色(r,g,b)的结构化数组(★★☆)

  • (提示: dtype)

参考答案

#参考答案
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                   ('y', float, 1)]),
                   ('color',    [ ('r', float, 1),
                                  ('g', float, 1),
                                  ('b', float, 1)])])
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.))]

52. 对一个表示坐标形状为(100,2)的随机向量,找到点与点的距离(★★☆)

  • (提示: np.atleast_2d, T, np.sqrt)
#np.atleast_2d(*arys)
np.atleast_2d(3.0)

输出结果

array([[3.]])
x = np.arange(3.0)
np.atleast_2d(x)

输出结果

array([[0., 1., 2.]])
np.atleast_2d(1, [1, 2], [[1, 2]])

输出结果

[array([[1]]), array([[1, 2]]), array([[1, 2]])]

参考答案

#参考答案
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print (D)

输出结果

[[0.         0.29070406 0.32362647 0.67865678 0.83707011 0.35972606
  0.38789831 0.60723344 0.30546822 0.45373561]
 [0.29070406 0.         0.3434642  0.73829603 1.03383445 0.08585908
  0.64530381 0.8612648  0.31446227 0.73726371]
 [0.32362647 0.3434642  0.         0.3984726  0.71940814 0.42539381
  0.44012903 0.62091165 0.02902795 0.58394142]
 [0.67865678 0.73829603 0.3984726  0.         0.48782049 0.81660089
  0.54621201 0.59527603 0.42716232 0.70240421]
 [0.83707011 1.03383445 0.71940814 0.48782049 0.         1.11969336
  0.48296815 0.33042144 0.74442429 0.55519457]
 [0.35972606 0.08585908 0.42539381 0.81660089 1.11969336 0.
  0.72641834 0.94358782 0.39654632 0.81184913]
 [0.38789831 0.64530381 0.44012903 0.54621201 0.48296815 0.72641834
  0.         0.2195894  0.4499221  0.16062628]
 [0.60723344 0.8612648  0.62091165 0.59527603 0.33042144 0.94358782
  0.2195894  0.         0.63661968 0.23057319]
 [0.30546822 0.31446227 0.02902795 0.42716232 0.74442429 0.39654632
  0.4499221  0.63661968 0.         0.5896036 ]
 [0.45373561 0.73726371 0.58394142 0.70240421 0.55519457 0.81184913
  0.16062628 0.23057319 0.5896036  0.        ]]

参考答案

# 方法2
# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial
D = scipy.spatial.distance.cdist(Z,Z)
print (D)

输出结果

[[0.         0.29070406 0.32362647 0.67865678 0.83707011 0.35972606
  0.38789831 0.60723344 0.30546822 0.45373561]
 [0.29070406 0.         0.3434642  0.73829603 1.03383445 0.08585908
  0.64530381 0.8612648  0.31446227 0.73726371]
 [0.32362647 0.3434642  0.         0.3984726  0.71940814 0.42539381
  0.44012903 0.62091165 0.02902795 0.58394142]
 [0.67865678 0.73829603 0.3984726  0.         0.48782049 0.81660089
  0.54621201 0.59527603 0.42716232 0.70240421]
 [0.83707011 1.03383445 0.71940814 0.48782049 0.         1.11969336
  0.48296815 0.33042144 0.74442429 0.55519457]
 [0.35972606 0.08585908 0.42539381 0.81660089 1.11969336 0.
  0.72641834 0.94358782 0.39654632 0.81184913]
 [0.38789831 0.64530381 0.44012903 0.54621201 0.48296815 0.72641834
  0.         0.2195894  0.4499221  0.16062628]
 [0.60723344 0.8612648  0.62091165 0.59527603 0.33042144 0.94358782
  0.2195894  0.         0.63661968 0.23057319]
 [0.30546822 0.31446227 0.02902795 0.42716232 0.74442429 0.39654632
  0.4499221  0.63661968 0.         0.5896036 ]
 [0.45373561 0.73726371 0.58394142 0.70240421 0.55519457 0.81184913
  0.16062628 0.23057319 0.5896036  0.        ]]

53. 如何将32位的浮点数(float)转换为对应的整数(integer)?

  • (提示: astype(copy=False))

参考答案

#参考答案
Z = np.arange(10, dtype=np.float32)
print(Z,type(Z),Z.dtype.name)
Z = Z.astype(np.int32, copy=False)
print(Z,type(Z),Z.dtype.name)

输出结果

[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] <class 'numpy.ndarray'> float32
[0 1 2 3 4 5 6 7 8 9] <class 'numpy.ndarray'> int32

54. 如何读取以下文件? (★★☆)

  • (提示: np.genfromtxt)
  • https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html

参考答案

from io import StringIO
import numpy as np
#Comma delimited file with mixed dtype
s = StringIO(u"1,1.3,abcde")
data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ('mystring','S5')], delimiter=",")
data

输出结果

array((1, 1.3, b'abcde'),
      dtype=[('myint', '), ('myfloat', '), ('mystring', 'S5')])
#Using dtype = None
_ = s.seek(0) # needed for StringIO example only
data = np.genfromtxt(s, dtype=None,names = ['myint','myfloat','mystring'], delimiter=",")
data

输出结果

array((b'11.3abcde',), dtype=[('myint', 'S9')])
#Specifying dtype and names
_ = s.seek(0)
data = np.genfromtxt(s, dtype="i8,f8,S5",names=['myint','myfloat','mystring'], delimiter=",")
data

输出结果

array((1, 1.3, b'abcde'),
      dtype=[('myint', '), ('myfloat', '), ('mystring', 'S5')])
#An example with fixed-width columns
s = StringIO(u"11.3abcde")
data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],delimiter=[1,3,5])
data

输出结果

array((1, 1.3, b'abcde'),
      dtype=[('intvar', '), ('fltvar', '), ('strvar', 'S5')])
#An example to show comments
f = StringIO('''text,# of charshello world,11numpy,5''')
np.genfromtxt(f, dtype='S12,S12', delimiter=',') 

输出结果

array((b'text', b''), dtype=[('f0', 'S12'), ('f1', 'S12')])

55. 对于numpy数组,enumerate的等价操作是什么?(★★☆)

  • (提示: np.ndenumerate, np.ndindex)
#enumerate(iterable, start=0)
array50 = np.random.random(10)
print(array50)
enumerate(array50)

输出结果

[0.83578624 0.16400743 0.52875841 0.26802722 0.91601738 0.26684625
 0.18977961 0.80121331 0.47645511 0.9602076 ]
<enumerate at 0x1ad29a6c8c0>
#np.ndenumerate(arr)
a = np.array([[1, 2], [3, 4]])
for index, x in np.ndenumerate(a):
    print(index, x)

输出结果

(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
#np.ndindex(*shape)
# dimensions as individual arguments
for index in np.ndindex(3, 2, 1):
    print(index)

输出结果

(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
#same dimensions - but in a tuple (3, 2, 1)
for index in np.ndindex((3, 2, 1)):
    print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

参考答案

#参考答案
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
for index in np.ndindex(Z.shape):
    print (index, Z[index])

输出结果

(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

56. 生成一个通用的二维Gaussian-like数组 (★★☆)

  • (提示: np.meshgrid, np.exp)

参考答案

#参考答案
#np.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print (G)

输出结果

[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]]

57. 对一个二维数组,如何在其内部随机放置p个元素? (★★☆)

  • (提示: np.put, np.random.choice)
#np.put(a, ind, v, mode='raise')
a = np.arange(5)
np.put(a, [0, 2], [-44, -55])
a

输出结果

array([-44,   1, -55,   3,   4])
a = np.arange(5)
np.put(a, 22, -5, mode='clip')
a

输出结果

array([ 0,  1,  2,  3, -5])
#np.random.choice(a, size=None, replace=True, p=None)

#Generate a uniform random sample from np.arange(5) of size 3:
print(np.random.choice(5, 3))

#等价于np.random.randint(0,5,3)
print(np.random.randint(0,5,3))

输出结果

[4 0 1]
[4 3 0]
#Generate a non-uniform random sample from np.arange(5) of size 3:
np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 2, 3])
#Generate a uniform random sample from np.arange(5) of size 3 without
#replacement:
print(np.random.choice(5, 3, replace=False))

#等价于np.random.permutation(np.arange(5))[:3]
print(np.random.permutation(np.arange(5))[:3])

输出结果

[3 4 1]
[4 0 1]
#Generate a non-uniform random sample from np.arange(5) of size
#3 without replacement:
np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])

输出结果

array([2, 3, 0])
#Any of the above can be repeated with an arbitrary array-like
#instead of just integers. For instance:
aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])

输出结果

array(['rabbit', 'Christopher', 'pooh', 'pooh', 'pooh'], dtype=')

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