Numpy-100

numpy

参考

1. 导入numpy库并简写为 np

1
import numpy as np

2. 打印numpy的版本和配置说明

1
2
print(np.__version__)
print(np.show_config())
1.19.2
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
None

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

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

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

1
print("%d bytes" % (Z.size * Z.itemsize))
80 bytes

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

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

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

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

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

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

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

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

1
2
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元素的位置索引

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

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

1
2
Z = np.eye(3)
print(Z)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

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

1
2
Z = np.random.random((3, 3, 3))
print(Z)
[[[0.88486955 0.5490597  0.59669197]
  [0.35137688 0.48379957 0.07091021]
  [0.62127269 0.51806167 0.03852795]]

 [[0.15854486 0.05115505 0.20431851]
  [0.11087782 0.21286826 0.80180936]
  [0.73353315 0.45160643 0.76325029]]

 [[0.3903262  0.44422448 0.95099903]
  [0.28599768 0.48745533 0.05721719]
  [0.47329799 0.00279801 0.07081437]]]

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

1
2
3
Z = np.random.random((10, 10))
Zmax, Zmin = Z.max(), Z.min()
print(Zmax, Zmin)
0.9916690090908562 0.0065094427825592716

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

1
2
Z = np.random.random(30)
print(Z.mean())
0.5447235064512149

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

1
2
3
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填充的边界?

1
2
3
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. 以下表达式运行的结果分别是什么?

1
0 * np.nan
nan
1
np.nan == np.nan
False
1
np.inf > np.nan
False
1
np.nan - np.nan
nan
1
0.3 == 3 * 0.1
False

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

1
2
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 的矩阵,并且设置成棋盘样式

1
2
3
4
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)是什么?

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

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

1
2
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的随机矩阵做归一化

1
2
3
4
5
6
Z = np.random.random((5,5))
print(Z)
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print('归一化:')
print(Z)
[[0.38425685 0.53708226 0.6652044  0.53846365 0.52572921]
 [0.35578247 0.56376841 0.51732071 0.64696521 0.48704011]
 [0.71386634 0.11482216 0.35562303 0.49511748 0.94909796]
 [0.61600517 0.55368581 0.23454672 0.05183324 0.06497491]
 [0.9731188  0.89971985 0.67555374 0.70371238 0.97471339]]
归一化:
[[0.36020237 0.52579853 0.6646271  0.52729535 0.51349677]
 [0.32934854 0.55471469 0.50438561 0.64486377 0.47157463]
 [0.71735545 0.06825255 0.32917577 0.48032698 0.97224404]
 [0.61131658 0.54378954 0.19798181 0.         0.01423985]
 [0.99827216 0.91873968 0.67584128 0.70635297 1.        ]]

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

1
2
3
4
5
color = np.dtype([("r", np.ubyte),
("g", np.ubyte),
("b", np.ubyte),
("a", np.ubyte)])
color
dtype([('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')])

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

1
2
3
4
Z1, Z2 = np.ones((5, 3)), np.ones((3, 2))
print(np.dot(Z1, Z2))
print('----或-----')
print(Z1@Z2)
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]
----或-----
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]

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

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

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

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

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

1
2
Z = np.arange(5)
Z ** Z
[0 1 2 3 4]





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

ValueError                                Traceback (most recent call last)

<ipython-input-82-287e9cf34c9f> in <module>
      1 Z = np.arange(5)
----> 2 Z<Z>Z


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

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

1
np.array(0) / np.array(0)
/Users/admin/.virtualenvs/numpy/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
  """Entry point for launching an IPython kernel.





nan
1
np.array(0) // np.array(0)
/Users/admin/.virtualenvs/numpy/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in floor_divide
  """Entry point for launching an IPython kernel.





0
1
np.array([np.nan]).astype(int).astype(float)
array([-9.22337204e+18])

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

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

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

1
2
3
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
[1 6 7 9]

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

1
2
3
4
5
6
# 自杀模式
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# 恢复理智
_ = np.seterr(**defaults)
1
2
with np.errstate(divide='ignore'):  
Z = np.ones(1) / 0

32. 下面的表达式是正确的吗?

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

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

1
2
3
4
5
6
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print ("昨天 " + str(yesterday))
print ("今天 " + str(today))
print ("明天 "+ str(tomorrow))
昨天 2020-10-22
今天  2020-10-23
明天 2020-10-24

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

1
np.arange('2016-07', '2016-08', dtype='datetime64[D]')
array(['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'], dtype='datetime64[D]')

35. 如何直接在位计算(A+B)*(-A/2)(不建立副本)?

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

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

1
2
Z = np.random.uniform(0,10,10)
print(Z)
[9.65002236 2.02077988 7.90182176 0.95615672 2.4638734  0.74263585
 5.99876609 7.14737062 6.2959432  3.42980839]
1
print (Z - Z%1)
[9. 2. 7. 0. 2. 0. 5. 7. 6. 3.]
1
print (np.floor(Z))
[9. 2. 7. 0. 2. 0. 5. 7. 6. 3.]
1
print (np.ceil(Z)-1)
[9. 2. 7. 0. 2. 0. 5. 7. 6. 3.]
1
print (Z.astype(int))
[9 2 7 0 2 0 5 7 6 3]
1
print (np.trunc(Z))
[9. 2. 7. 0. 2. 0. 5. 7. 6. 3.]

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

1
2
3
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个整数的函数,来构建一个数组

1
2
3
4
5
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

1
2
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的随机向量,并将其排序

1
2
3
Z = np.random.random(10)
Z.sort()
print (Z)
[0.0824115  0.08352975 0.3346753  0.40580722 0.44177301 0.50663776
 0.59050701 0.75991226 0.87806887 0.9703208 ]

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

1
2
Z = np.arange(10)
np.add.reduce(Z)
45

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

1
2
3
4
5
6
7
8
9
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
# 假设数组具有相同的形状和值比较的容忍度
equal = np.allclose(A,B)
print(equal)

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

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

1
2
3
Z = np.zeros(10)  
Z.flags.writeable = False
Z[0] = 1
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-116-29348be95821> in <module>
      1 Z = np.zeros(10)
      2 Z.flags.writeable = False
----> 3 Z[0] = 1


ValueError: assignment destination is read-only

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

1
2
3
4
5
6
7
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(Z)
print (R)
print (T)
[[0.99192868 0.50024495]
 [0.02988894 0.01550554]
 [0.27221793 0.89725926]
 [0.60590261 0.12484057]
 [0.98140292 0.25029343]
 [0.18798725 0.41865512]
 [0.36612678 0.3256918 ]
 [0.1141495  0.31578922]
 [0.547363   0.59282924]
 [0.29013267 0.12039521]]
[1.11093093 0.03367151 0.93764427 0.61863005 1.0128171  0.45892409
 0.49002446 0.33578704 0.8068784  0.31412095]
[0.467094   0.47855207 1.27623394 0.20319708 0.24971312 1.14875224
 0.7270172  1.22393672 0.82525299 0.39334121]

45. 创建一个长度为10的向量,并将向量中最大值替换为0

1
2
3
Z = np.random.random(10)
Z[Z.argmax()] = 0
print (Z)
[0.55832328 0.4353952  0.13261811 0.60633258 1.         0.46403717
 0.37241254 0.38561917 0.82815613 0.88807826]

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

1
2
3
4
5
Z = np.zeros((5,5), [('x',float),('y',float)])
print(Z)
print(Z.dtype)
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), np.linspace(0,1,5))
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.)]]
[('x', '<f8'), ('y', '<f8')]





array([[(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.  )]], dtype=[('x', '<f8'), ('y', '<f8')])

47. 给定两个数组X和Y,构造Cauchy矩阵C (Cij =1/(xi - yj))

1
2
3
4
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.163637117973

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

1
2
3
4
5
6
7
8
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. 如何打印一个数组中的所有数值?

1
2
3
p.set_printoptions(threshold=np.nan)
Z = np.zeros((16,16))
print (Z)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-136-16a071ac8100> in <module>
----> 1 p.set_printoptions(threshold=np.nan)
      2 # Z = np.zeros((16,16))
      3 # print (Z)


NameError: name 'p' is not defined

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

1
2
3
4
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print (Z[index])
59

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

1
2
3
4
5
6
Z = np.zeros(10, [ ('position', [ ('x', float),
('y', float)]),
('color', [ ('r', float),
('g', float),
('b', float)])])
Z
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.))],
      dtype=[('position', [('x', '<f8'), ('y', '<f8')]), ('color', [('r', '<f8'), ('g', '<f8'), ('b', '<f8')])])

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

1
2
3
4
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.68605697 0.62122652 0.40530072 0.73015265 0.09355197
  0.56261515 0.51426855 0.41227321 0.85367183]
 [0.68605697 0.         0.10265723 0.28166536 0.64689843 0.73311637
  0.80907921 0.32712431 0.60162844 0.50010966]
 [0.62122652 0.10265723 0.         0.2312003  0.55079669 0.65895081
  0.70673619 0.34824116 0.5011675  0.43109473]
 [0.40530072 0.28166536 0.2312003  0.         0.61033959 0.45844664
  0.64946237 0.22328532 0.42686992 0.59168416]
 [0.73015265 0.64689843 0.55079669 0.61033959 0.         0.69214416
  0.33216102 0.8274823  0.32343075 0.28094981]
 [0.09355197 0.73311637 0.65895081 0.45844664 0.69214416 0.
  0.49087977 0.59249732 0.36881779 0.84414133]
 [0.56261515 0.80907921 0.70673619 0.64946237 0.33216102 0.49087977
  0.         0.8673326  0.22259532 0.59768751]
 [0.51426855 0.32712431 0.34824116 0.22328532 0.8274823  0.59249732
  0.8673326  0.         0.64545461 0.77079322]
 [0.41227321 0.60162844 0.5011675  0.42686992 0.32343075 0.36881779
  0.22259532 0.64545461 0.         0.50877578]
 [0.85367183 0.50010966 0.43109473 0.59168416 0.28094981 0.84414133
  0.59768751 0.77079322 0.50877578 0.        ]]

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

1
2
3
Z = np.arange(10, dtype=np.int32)
Z = Z.astype(np.float32, copy=False)
print (Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

54. 如何读取以下文件?

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

1
2
3
4
5
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print (index, value)
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
(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数组

1
2
3
4
5
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个元素?

1
2
3
4
5
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print (Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 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. 0. 0. 0. 0. 0. 0. 0.]]

58. 减去一个矩阵中的每一行的平均值

1
2
3
4
X = np.random.rand(5, 10)
# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)
print(Y)
[[-0.22370269  0.29733747  0.03664633 -0.11929707  0.38934825 -0.2316397
  -0.27949186  0.10002169  0.27864595 -0.24786837]
 [-0.00062429  0.37487829 -0.02288536 -0.49889723 -0.39944991  0.01501358
  -0.00573352  0.38315633  0.33032148 -0.17577937]
 [-0.37684235  0.09168961  0.32210956 -0.25418135 -0.14166652  0.39539008
  -0.18467775  0.14629638 -0.26168209  0.26356442]
 [ 0.29264838 -0.14639492  0.1428065   0.27245024 -0.03056353 -0.03918195
  -0.16229655  0.00562351 -0.05273503 -0.28235666]
 [-0.2284848  -0.28808201 -0.15736303 -0.05439054 -0.22746016  0.1996868
  -0.19907649  0.55945475  0.50459159 -0.10887613]]
  • 方法2
1
2
3
# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)
print (Y)
[[-0.22370269  0.29733747  0.03664633 -0.11929707  0.38934825 -0.2316397
  -0.27949186  0.10002169  0.27864595 -0.24786837]
 [-0.00062429  0.37487829 -0.02288536 -0.49889723 -0.39944991  0.01501358
  -0.00573352  0.38315633  0.33032148 -0.17577937]
 [-0.37684235  0.09168961  0.32210956 -0.25418135 -0.14166652  0.39539008
  -0.18467775  0.14629638 -0.26168209  0.26356442]
 [ 0.29264838 -0.14639492  0.1428065   0.27245024 -0.03056353 -0.03918195
  -0.16229655  0.00562351 -0.05273503 -0.28235666]
 [-0.2284848  -0.28808201 -0.15736303 -0.05439054 -0.22746016  0.1996868
  -0.19907649  0.55945475  0.50459159 -0.10887613]]

59. 如何通过第n列对一个数组进行排序?

1
2
3
Z = np.random.randint(0,10,(3,3))
print (Z)
Z[Z[:,1].argsort()]
[[5 4 8]
 [1 0 2]
 [3 1 9]]





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

60. 如何检查一个二维数组是否有空列?

1
2
Z = np.random.randint(0,3,(3,10))
print ((~Z.any(axis=0)).any())
False

61. 从数组中的给定值中找出最近的值

1
2
3
4
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print (m)
0.5589928708513087

62. 如何用迭代器(iterator)计算两个分别具有形状(1,3)和(3,1)的数组?

1
2
3
4
5
6
A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it:
z[...] = x + y
print (it.operands[2])
[[0 1 2]
 [1 2 3]
 [2 3 4]]

63. 创建一个具有name属性的数组类

1
2
3
4
5
6
7
8
9
10
11
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")

Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
range_10

64. 考虑一个给定的向量,如何对由第二个向量索引的每个元素加1(小心重复的索引)?

1
2
3
4
Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)
[3. 2. 2. 2. 3. 3. 3. 5. 1. 6.]
  • 方法2
1
2
np.add.at(Z, I, 1)
print(Z)
[ 5.  3.  3.  3.  5.  5.  5.  9.  1. 11.]

65. 根据索引列表(I),如何将向量(X)的元素累加到数组(F)?

1
2
3
4
X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
print (F)
[0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]

66. 考虑一个(dtype=ubyte) 的 (w,h,3)图像,计算其唯一颜色的数量

1
2
3
4
5
6
7
w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
#Note that we should compute 256*256 first.
#Otherwise numpy will only promote F.dtype to 'uint16' and overfolw will occur
F = I[...,0]*(256*256) + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print (n)
8

67. 考虑一个四维数组,如何一次性计算出最后两个轴(axis)的和?

1
2
3
4
A = np.random.randint(0,10,(3,4,3,4))
# solution by passing a tuple of axes (introduced in numpy 1.7.0)
sum = A.sum(axis=(-2,-1))
print (sum)
[[35 63 58 52]
 [64 43 51 40]
 [32 61 61 67]]
  • 方法2
1
2
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print (sum)
[[35 63 58 52]
 [64 43 51 40]
 [32 61 61 67]]

68. 考虑一个一维向量D,如何使用相同大小的向量S来计算D子集的均值?

1
2
3
4
5
6
D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print (D_means)
[0.40003185 0.74168757 0.53029708 0.57672923 0.55116799 0.55260023
 0.5413465  0.37198828 0.57577261 0.54925535]
  • 方法2
1
2
# import pandas as pd
# print(pd.Series(D).groupby(S).mean())

69. 如何获得点积 dot prodcut的对角线?

1
2
3
4
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
# # slow version
np.diag(np.dot(A, B))
array([1.90221076, 0.73114449, 0.73911389, 0.71844659, 1.71777083])
  • 方法2
1
np.sum(A * B.T, axis=1)
array([1.90221076, 0.73114449, 0.73911389, 0.71844659, 1.71777083])
  • 方法3
1
np.einsum("ij,ji->i", A, B)
array([1.90221076, 0.73114449, 0.73911389, 0.71844659, 1.71777083])

70. 考虑一个向量[1,2,3,4,5],如何建立一个新的向量,在这个新向量中每个值之间有3个连续的零?

1
2
3
4
5
Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print (Z0)
[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]

71. 考虑一个维度(5,5,3)的数组,如何将其与一个(5,5)的数组相乘?

1
2
3
A = np.ones((5,5,3))
B = 2*np.ones((5,5))
print (A * B[:,:,None])
[[[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]]

72. 如何对一个数组中任意两行做交换?

1
2
3
A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print (A)
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

73. 考虑一个可以描述10个三角形的triplets,找到可以分割全部三角形的line segment

1
2
3
4
5
6
7
faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print (G)
[(11, 33) (11, 44) (13, 25) (13, 87) (14, 39) (14, 55) (16, 84) (16, 96)
 (17, 84) (17, 95) (18, 35) (18, 81) (21, 42) (21, 49) (23, 92) (23, 98)
 (25, 87) (33, 44) (35, 81) (39, 55) (42, 49) (49, 80) (49, 92) (59, 70)
 (59, 77) (70, 77) (80, 92) (84, 95) (84, 96) (92, 98)]

74. 给定一个二进制的数组C,如何产生一个数组A满足np.bincount(A)==C

1
2
3
C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print (A)
[1 1 2 3 4 4 6]

75. 如何通过滑动窗口计算一个数组的平均数?

1
2
3
4
5
6
7
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)

print(moving_average(Z, n=3))
[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18.]

76. 考虑一个一维数组Z,构建一个二维数组,其第一行为(Z[0],Z[1],Z[2]),然后每个后续行移动1(最后一行应该为(Z[-3],Z[-2],Z[-1])

1
2
3
4
5
6
7
8
9
from numpy.lib import stride_tricks

def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.itemsize, a.itemsize)
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)

print (Z)
[[0 1 2]
 [1 2 3]
 [2 3 4]
 [3 4 5]
 [4 5 6]
 [5 6 7]
 [6 7 8]
 [7 8 9]]

77. 如何对布尔值取反,或者原位(in-place)改变浮点数的符号(sign)?

1
2
Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
       1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0,
       0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
       0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0])
1
2
Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)
array([ 0.23689681, -0.1057382 , -0.57698282, -0.83485527, -0.56592412,
        0.52906058,  0.87636873,  0.79456037, -0.84943243, -0.02862234,
       -0.27874639,  0.53982869, -0.92819707, -0.84933822, -0.72655128,
       -0.27991263, -0.38821443, -0.89064306, -0.6238352 , -0.70331099,
        0.33032683, -0.62906234, -0.60486077,  0.19187415, -0.07665583,
        0.94393027,  0.94226737,  0.78399481,  0.03917581, -0.97886888,
        0.3023522 ,  0.8854273 ,  0.43260069, -0.5108798 ,  0.08447692,
        0.8094311 , -0.02961588,  0.43797035,  0.53489813, -0.23148178,
        0.50132491, -0.11907561, -0.41351587,  0.77849175, -0.08522882,
        0.01426253,  0.52019255, -0.10827315, -0.37614668,  0.77433187,
        0.36585315, -0.68845912, -0.59425059,  0.79725862,  0.8208273 ,
       -0.71978436, -0.02122081,  0.19379665, -0.06794473, -0.3887197 ,
       -0.32546326,  0.73797113, -0.17697576, -0.21162741,  0.71927392,
       -0.6944913 ,  0.05130906,  0.87329243,  0.65334172,  0.73613569,
       -0.27170543,  0.10374602, -0.24059875, -0.72685295,  0.46246967,
        0.0853352 ,  0.38266084, -0.18466922, -0.1979213 , -0.24355838,
       -0.4658587 , -0.65447698, -0.21552133,  0.60630034,  0.76115048,
       -0.45606078, -0.89412734,  0.5211218 ,  0.37955327,  0.42356571,
        0.7953681 , -0.43269998, -0.9698459 ,  0.95951107, -0.24806371,
        0.35883848,  0.17046673, -0.31071932, -0.23371407, -0.45192508])

78. 考虑两组点集P0和P1去描述一组线(二维)和一个点p,如何计算点p到每一条线 i (P0[i],P1[i])的距离?

1
2
3
4
5
6
7
8
9
10
11
12
13
def distance(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))

P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))

print (distance(P0, P1, p))
[6.73003936 3.25658553 8.43503749 8.03999863 2.52898731 2.10311161
 1.37978063 0.66841085 6.59364144 1.56923099]

79.考虑两组点集P0和P1去描述一组线(二维)和一组点集P,如何计算每一个点 j(P[j]) 到每一条线 i (P0[i],P1[i])的距离?

1
2
3
4
5
# based on distance function from previous question
P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print (np.array([distance(P0,P1,p_i) for p_i in p]))
[[13.07041481  0.34376075 16.58732696 14.87969545  4.11962738  5.42144091
  12.11842537  3.68644762 12.40317974  3.09689636]
 [ 8.31670675 10.27424599  3.2826011   3.52519444 10.00075179  2.84898481
   9.65299862 11.41398094  7.30142854  1.88829117]
 [ 6.77924397 10.58975518  1.62351305  1.82484002  8.59935901  1.34441665
   8.19193867  9.71657604  6.60203043  3.04720539]
 [ 5.31162447  7.15368953 10.15848703  9.47767034  2.94628246  5.49623871
   3.86868708  0.27595815  2.83153155  6.28099959]
 [ 3.44438221  4.17789976  7.58912946  6.50592271  7.00008457  1.4819549
   2.34424003  3.25599879  3.70548935  2.2971877 ]
 [ 2.36688408  3.25851654  1.37656162  0.17449453 12.04923635  3.97454356
   3.20458239  9.51687426  0.88033642  1.81179476]
 [ 1.4752091  12.1742076   4.20617443  4.21460366  3.31482283  4.26452794
   3.19931119  3.57944931  4.51890055  7.53817263]
 [ 5.46643964  8.63921896 10.63642071 10.15728999  1.48642797  6.87406001
   3.8756232   1.27141727  1.93560503  7.84232163]
 [ 6.41793965  0.50870998  9.88281153  8.29794915  8.17165084  0.78199922
   5.58269127  2.40028245  7.90280833  0.28608886]
 [10.37689182  3.50154975 14.62120512 13.43886767  2.58517684  6.4955299
   9.13465077  3.20719531  8.25437731  5.43698872]]

80.考虑一个任意数组,编写一个函数来提取形状固定且以给定元素为中心的子部分(必要时使用填充值填充)

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
Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill = 0
position = (1,1)

R = np.ones(shape, dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)

R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2

R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()

r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]
print (Z)
print (R)
[[1 8 6 0 0 3 1 3 0 5]
 [6 3 1 0 6 4 4 0 4 1]
 [1 4 8 9 6 5 0 8 1 2]
 [7 5 6 8 6 1 1 8 4 0]
 [7 9 1 4 9 5 1 5 8 1]
 [3 0 8 9 1 7 2 5 6 7]
 [7 5 0 1 1 3 8 7 0 4]
 [5 0 1 4 6 8 7 3 7 7]
 [0 9 7 4 8 4 9 0 0 6]
 [5 5 9 7 5 4 4 1 8 5]]
[[0 0 0 0 0]
 [0 1 8 6 0]
 [0 6 3 1 0]
 [0 1 4 8 9]
 [0 7 5 6 8]]


/Users/admin/.virtualenvs/numpy/lib/python3.7/site-packages/ipykernel_launcher.py:23: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.

81. 考虑一个数组Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14],如何生成一个数组R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], …,[11,12,13,14]]?

1
2
3
Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print (R)
[[ 1  2  3  4]
 [ 2  3  4  5]
 [ 3  4  5  6]
 [ 4  5  6  7]
 [ 5  6  7  8]
 [ 6  7  8  9]
 [ 7  8  9 10]
 [ 8  9 10 11]
 [ 9 10 11 12]
 [10 11 12 13]
 [11 12 13 14]]

82. 计算一个矩阵的秩

1
2
3
4
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print (rank)
10

83. 如何找到一个数组中出现频率最高的值?

1
2
Z = np.random.randint(0,10,50)
print (np.bincount(Z).argmax())
3

84. 从一个10x10的矩阵中提取出连续的3x3区块

1
2
3
4
5
6
Z = np.random.randint(0,5,(10,10))
n = 3
i = 1 + (Z.shape[0]-3)
j = 1 + (Z.shape[1]-3)
C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print (C)
[[[[3 2 0]
   [2 2 2]
   [1 1 4]]

  [[2 0 3]
   [2 2 2]
   [1 4 4]]

  [[0 3 1]
   [2 2 2]
   [4 4 4]]

  [[3 1 3]
   [2 2 2]
   [4 4 2]]

  [[1 3 1]
   [2 2 0]
   [4 2 0]]

  [[3 1 1]
   [2 0 1]
   [2 0 1]]

  [[1 1 3]
   [0 1 3]
   [0 1 3]]

  [[1 3 0]
   [1 3 2]
   [1 3 1]]]


 [[[2 2 2]
   [1 1 4]
   [3 2 0]]

  [[2 2 2]
   [1 4 4]
   [2 0 2]]

  [[2 2 2]
   [4 4 4]
   [0 2 4]]

  [[2 2 2]
   [4 4 2]
   [2 4 3]]

  [[2 2 0]
   [4 2 0]
   [4 3 1]]

  [[2 0 1]
   [2 0 1]
   [3 1 3]]

  [[0 1 3]
   [0 1 3]
   [1 3 2]]

  [[1 3 2]
   [1 3 1]
   [3 2 4]]]


 [[[1 1 4]
   [3 2 0]
   [0 4 3]]

  [[1 4 4]
   [2 0 2]
   [4 3 1]]

  [[4 4 4]
   [0 2 4]
   [3 1 4]]

  [[4 4 2]
   [2 4 3]
   [1 4 4]]

  [[4 2 0]
   [4 3 1]
   [4 4 4]]

  [[2 0 1]
   [3 1 3]
   [4 4 2]]

  [[0 1 3]
   [1 3 2]
   [4 2 1]]

  [[1 3 1]
   [3 2 4]
   [2 1 1]]]


 [[[3 2 0]
   [0 4 3]
   [4 2 3]]

  [[2 0 2]
   [4 3 1]
   [2 3 0]]

  [[0 2 4]
   [3 1 4]
   [3 0 1]]

  [[2 4 3]
   [1 4 4]
   [0 1 4]]

  [[4 3 1]
   [4 4 4]
   [1 4 2]]

  [[3 1 3]
   [4 4 2]
   [4 2 3]]

  [[1 3 2]
   [4 2 1]
   [2 3 3]]

  [[3 2 4]
   [2 1 1]
   [3 3 2]]]


 [[[0 4 3]
   [4 2 3]
   [4 1 2]]

  [[4 3 1]
   [2 3 0]
   [1 2 4]]

  [[3 1 4]
   [3 0 1]
   [2 4 3]]

  [[1 4 4]
   [0 1 4]
   [4 3 4]]

  [[4 4 4]
   [1 4 2]
   [3 4 2]]

  [[4 4 2]
   [4 2 3]
   [4 2 1]]

  [[4 2 1]
   [2 3 3]
   [2 1 1]]

  [[2 1 1]
   [3 3 2]
   [1 1 3]]]


 [[[4 2 3]
   [4 1 2]
   [4 2 3]]

  [[2 3 0]
   [1 2 4]
   [2 3 4]]

  [[3 0 1]
   [2 4 3]
   [3 4 2]]

  [[0 1 4]
   [4 3 4]
   [4 2 4]]

  [[1 4 2]
   [3 4 2]
   [2 4 0]]

  [[4 2 3]
   [4 2 1]
   [4 0 3]]

  [[2 3 3]
   [2 1 1]
   [0 3 0]]

  [[3 3 2]
   [1 1 3]
   [3 0 4]]]


 [[[4 1 2]
   [4 2 3]
   [1 1 2]]

  [[1 2 4]
   [2 3 4]
   [1 2 1]]

  [[2 4 3]
   [3 4 2]
   [2 1 0]]

  [[4 3 4]
   [4 2 4]
   [1 0 3]]

  [[3 4 2]
   [2 4 0]
   [0 3 4]]

  [[4 2 1]
   [4 0 3]
   [3 4 0]]

  [[2 1 1]
   [0 3 0]
   [4 0 2]]

  [[1 1 3]
   [3 0 4]
   [0 2 4]]]


 [[[4 2 3]
   [1 1 2]
   [1 1 4]]

  [[2 3 4]
   [1 2 1]
   [1 4 3]]

  [[3 4 2]
   [2 1 0]
   [4 3 4]]

  [[4 2 4]
   [1 0 3]
   [3 4 3]]

  [[2 4 0]
   [0 3 4]
   [4 3 0]]

  [[4 0 3]
   [3 4 0]
   [3 0 2]]

  [[0 3 0]
   [4 0 2]
   [0 2 0]]

  [[3 0 4]
   [0 2 4]
   [2 0 1]]]]

85. 创建一个满足 Z[i,j] == Z[j,i]的子类

1
2
3
4
5
6
7
8
9
10
11
12
class Symetric(np.ndarray):
def __setitem__(self, index, value):
i,j = index
super(Symetric, self).__setitem__((i,j), value)
super(Symetric, self).__setitem__((j,i), value)

def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)

S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print (S)
[[ 2 12  8 13  5]
 [12  9 13 12  7]
 [ 8 13  0 42  6]
 [13 12 42  6  5]
 [ 5  7  6  5  1]]

86. 考虑p个 nxn 矩阵和一组形状为(n,1)的向量,如何直接计算p个矩阵的乘积(n,1)?

1
2
3
4
5
6
7
8
9
10
p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print (S)
# It works, because:
M is (p,n,n)
V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.
[[200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]]





False

87. 对于一个16x16的数组,如何得到一个区域(block-sum)的和(区域大小为4x4)?

1
2
3
4
5
Z = np.ones((16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
np.arange(0, Z.shape[1], k), axis=1)
print (S)
[[16. 16. 16. 16.]
 [16. 16. 16. 16.]
 [16. 16. 16. 16.]
 [16. 16. 16. 16.]]

88. 如何利用numpy数组实现Game of Life?

(提示: Game of Life)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def iterate(Z):
# Count neighbours
N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
Z[1:-1,0:-2] + Z[1:-1,2:] +
Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])

# Apply rules
birth = (N==3) & (Z[1:-1,1:-1]==0)
survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
Z[...] = 0
Z[1:-1,1:-1][birth | survive] = 1
return Z

Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z)
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]]

89. 如何找到一个数组的第n个最大值?

1
2
3
4
5
6
Z = np.arange(10000)
np.random.shuffle(Z)
n = 5

# Slow
print (Z[np.argsort(Z)[-n:]])
[9995 9996 9997 9998 9999]
  • 方法2
1
2
# # Fast
print (Z[np.argpartition(-Z,n)[:n]])
[9999 9998 9997 9996 9995]

90. 给定任意个数向量,创建笛卡尔积(每一个元素的每一种组合)

1
2
3
4
5
6
7
8
9
10
11
12
13
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)

ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T

for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]

return ix

print (cartesian(([1, 2, 3], [4, 5], [6, 7])))
[[1 4 6]
 [1 4 7]
 [1 5 6]
 [1 5 7]
 [2 4 6]
 [2 4 7]
 [2 5 6]
 [2 5 7]
 [3 4 6]
 [3 4 7]
 [3 5 6]
 [3 5 7]]

91. 如何从一个正常数组创建记录数组(record array)?

1
2
3
4
5
6
Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T,
names='col1, col2, col3',
formats = 'S8, f8, i8')
print (R)
[(b'Hello', 2.5, 3) (b'World', 3.6, 2)]

92. 考虑一个大向量Z, 用三种不同的方法计算它的立方

1
2
x = np.random.rand()
np.power(x,3)
0.000911010785045678
  • 方法2
1
x*x*x
0.000911010785045678

93. 考虑两个形状分别为(8,3) 和(2,2)的数组A和B. 如何在数组A中找到满足包含B中元素的行?(不考虑B中每行元素顺序)?

1
2
3
4
5
6
A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print (rows)
[1 4 6 7]

94. 考虑一个10x3的矩阵,分解出有不全相同值的行 (如 [2,2,3])

1
2
3
4
5
6
7
Z = np.random.randint(0,5,(10,3))
print (Z)

# solution for arrays of all dtypes (including string arrays and record arrays)
E = np.all(Z[:,1:] == Z[:,:-1], axis=1)
U = Z[~E]
print (U)
[[2 2 4]
 [2 0 4]
 [1 1 2]
 [3 0 2]
 [0 1 1]
 [2 4 0]
 [1 2 0]
 [1 3 2]
 [3 3 3]
 [3 1 1]]
[[2 2 4]
 [2 0 4]
 [1 1 2]
 [3 0 2]
 [0 1 1]
 [2 4 0]
 [1 2 0]
 [1 3 2]
 [3 1 1]]
  • 方法2
1
2
3
# soluiton for numerical arrays only, will work for any number of columns in Z
U = Z[Z.max(axis=1) != Z.min(axis=1),:]
print (U)
[[2 2 4]
 [2 0 4]
 [1 1 2]
 [3 0 2]
 [0 1 1]
 [2 4 0]
 [1 2 0]
 [1 3 2]
 [3 1 1]]

95. 将一个整数向量转换为matrix binary的表现形式

1
2
3
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 1 1]
 [0 0 0 0 1 1 1 1]
 [0 0 0 1 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]]
  • 方法2
1
# print (np.unpackbits(I[:, np.newaxis], axis=1))

96. 给定一个二维数组,如何提取出唯一的(unique)行?

1
2
3
4
5
Z = np.random.randint(0,2,(6,3))
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
_, idx = np.unique(T, return_index=True)
uZ = Z[idx]
print (uZ)
[[0 0 0]
 [0 1 0]
 [1 0 1]
 [1 1 0]
 [1 1 1]]

97. 考虑两个向量A和B,写出用einsum等式对应的inner, outer, sum, mul函数

1
2
3
4
A = np.random.uniform(0,1,10)
B = np.random.uniform(0,1,10)
print ('sum')
print (np.einsum('i->', A))# np.sum(A)
sum
3.9854151671792284
1
2
print ('A * B')
print (np.einsum('i,i->i', A, B)) # A * B
A * B
[0.28888653 0.60418484 0.41649239 0.09110476 0.06966387 0.43890848
 0.05302467 0.37448688 0.10099565 0.2354905 ]
1
2
print ('inner')
print (np.einsum('i,i', A, B)) # np.inner(A, B)
inner
2.673238575659151
1
2
print ('outer')
print (np.einsum('i,j->ij', A, B)) # np.outer(A, B)
outer
[[0.28888653 0.27775195 0.21538512 0.20511293 0.3347668  0.20453934
  0.24313786 0.25523188 0.3137035  0.30699418]
 [0.62840553 0.60418484 0.4685203  0.44617553 0.7282074  0.44492782
  0.52888994 0.55519766 0.68238908 0.66779451]
 [0.5586228  0.53709175 0.41649239 0.39662895 0.64734194 0.39551979
  0.47015815 0.49354447 0.60661162 0.59363774]
 [0.12831438 0.12336875 0.09566735 0.09110476 0.14869296 0.09084999
  0.10799425 0.11336603 0.1393373  0.13635723]
 [0.06011633 0.05779927 0.04482093 0.04268333 0.06966387 0.04256396
  0.05059619 0.05311291 0.06528066 0.06388448]
 [0.61990396 0.59601095 0.46218178 0.44013931 0.71835562 0.43890848
  0.52173469 0.54768651 0.67315718 0.65876005]
 [0.06300176 0.06057348 0.04697222 0.04473201 0.07300755 0.04460692
  0.05302467 0.05566219 0.06841396 0.06695076]
 [0.42386639 0.40752927 0.31602205 0.30095027 0.49118384 0.30010867
  0.35674204 0.37448688 0.46027889 0.45043469]
 [0.09300592 0.08942119 0.06934242 0.06603533 0.1077769  0.06585067
  0.07827731 0.08217094 0.10099565 0.09883561]
 [0.2216004  0.21305924 0.16521861 0.15733897 0.25679445 0.15689898
  0.18650731 0.19578444 0.24063712 0.2354905 ]]

98. 考虑一个由两个向量描述的路径(X,Y),如何用等距样例(equidistant samples)对其进行采样(sample)?

1
2
3
4
5
6
7
8
9
10
11
12
13
phi = np.arange(0, 10*np.pi, 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)

dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)
r[1:] = np.cumsum(dr) # integrate path
r_int = np.linspace(0, r.max(), 200) # regular spaced path
x_int = np.interp(r_int, r, x) # integrate path
y_int = np.interp(r_int, r, y)
print(x_int)
print(y_int)
[ 0.00000000e+00 -3.73131229e-01 -2.59817608e+00 -3.26212050e+00
 -2.18442687e+00 -2.98929946e-02  2.42923642e+00  4.54913599e+00
  5.92318348e+00  6.35117933e+00  5.82369277e+00  4.46259540e+00
  2.47320794e+00  1.09577220e-01 -2.36575300e+00 -4.71261671e+00
 -6.72701769e+00 -8.25541575e+00 -9.18486120e+00 -9.46381505e+00
 -9.11085788e+00 -8.12875279e+00 -6.63306046e+00 -4.69271059e+00
 -2.44736165e+00 -2.05444585e-02  2.46101146e+00  4.86841760e+00
  7.08937968e+00  9.02539126e+00  1.05948609e+01  1.17357250e+01
  1.24068974e+01  1.25885805e+01  1.22815267e+01  1.15053927e+01
  1.02963689e+01  8.70429550e+00  6.78948686e+00  4.61716636e+00
  2.25853448e+00 -1.98731680e-01 -2.68040566e+00 -5.11543300e+00
 -7.41973991e+00 -9.53891040e+00 -1.14237629e+01 -1.29919305e+01
 -1.42355069e+01 -1.51243232e+01 -1.56061571e+01 -1.57219415e+01
 -1.54217066e+01 -1.47579136e+01 -1.37255236e+01 -1.23634834e+01
 -1.07024632e+01 -8.78327367e+00 -6.65029558e+00 -4.35514246e+00
 -1.94290275e+00  5.28038914e-01  3.00985904e+00  5.45450275e+00
  7.80093594e+00  1.00179639e+01  1.20595602e+01  1.38732623e+01
  1.54564938e+01  1.67497894e+01  1.77435802e+01  1.84439878e+01
  1.87990820e+01  1.88271003e+01  1.85472755e+01  1.79378850e+01
  1.70105456e+01  1.58085777e+01  1.43501808e+01  1.26222364e+01
  1.06905445e+01  8.58498641e+00  6.33562529e+00  3.96179025e+00
  1.51802643e+00 -9.61699044e-01 -3.44349301e+00 -5.88951759e+00
 -8.26006582e+00 -1.05270865e+01 -1.26610269e+01 -1.46343020e+01
 -1.64206033e+01 -1.79708499e+01 -1.92894561e+01 -2.03605967e+01
 -2.11716587e+01 -2.17133504e+01 -2.19797677e+01 -2.19626531e+01
 -2.16476737e+01 -2.10622561e+01 -2.02145809e+01 -1.91158467e+01
 -1.77800930e+01 -1.62239930e+01 -1.44666197e+01 -1.25291882e+01
 -1.04347777e+01 -8.20773276e+00 -5.86978851e+00 -3.45563299e+00
 -9.92556869e-01  1.49191203e+00  3.97031733e+00  6.41557503e+00
  8.80126359e+00  1.11019001e+01  1.32931995e+01  1.53523150e+01
  1.72580567e+01  1.89910866e+01  2.05340895e+01  2.18719167e+01
  2.29917039e+01  2.38829603e+01  2.45376309e+01  2.49501314e+01
  2.51173551e+01  2.50386548e+01  2.47157984e+01  2.41529019e+01
  2.33563391e+01  2.23346314e+01  2.10983193e+01  1.96598169e+01
  1.80332532e+01  1.62343003e+01  1.42799934e+01  1.21885425e+01
  9.97914013e+00  7.67176574e+00  5.28699023e+00  2.84441658e+00
  3.68190102e-01 -2.11846865e+00 -4.59426061e+00 -7.03829202e+00
 -9.43024209e+00 -1.17505186e+01 -1.39803999e+01 -1.61021634e+01
 -1.80991985e+01 -1.99561058e+01 -2.16587804e+01 -2.31850397e+01
 -2.45166960e+01 -2.56568097e+01 -2.65976904e+01 -2.73332424e+01
 -2.78589555e+01 -2.81718833e+01 -2.82706110e+01 -2.81552119e+01
 -2.78066635e+01 -2.72341677e+01 -2.64578863e+01 -2.54844118e+01
 -2.43214986e+01 -2.29779690e+01 -2.14636172e+01 -1.97837046e+01
 -1.79341987e+01 -1.59545785e+01 -1.38585628e+01 -1.16602783e+01
 -9.37416511e+00 -7.01488958e+00 -4.59184632e+00 -2.12995331e+00
  3.50691071e-01  2.83498918e+00  5.30813450e+00  7.75565814e+00
  1.01522531e+01  1.24813227e+01  1.47337756e+01  1.68973642e+01
  1.89604991e+01  2.09071945e+01  2.26943693e+01  2.43420179e+01
  2.58422998e+01  2.71881423e+01  2.83731992e+01  2.93376609e+01
  3.01222558e+01  3.07280750e+01  3.11531219e+01  3.13960177e+01]
[ 0.00000000e+00  1.74026724e+00  9.81816584e-01 -1.34251287e+00
 -3.53191891e+00 -4.70449474e+00 -4.59573427e+00 -3.33831870e+00
 -1.28956083e+00  1.14234685e+00  3.55645601e+00  5.62188218e+00
  7.09389488e+00  7.82951803e+00  7.78700678e+00  6.99685666e+00
  5.55535240e+00  3.60417006e+00  1.30506373e+00 -1.15819722e+00
 -3.61328132e+00 -5.89130465e+00 -7.87065053e+00 -9.41689057e+00
 -1.04714836e+01 -1.09903787e+01 -1.09354306e+01 -1.03330912e+01
 -9.22690166e+00 -7.67489830e+00 -5.75257980e+00 -3.54832201e+00
 -1.15854355e+00  1.31709956e+00  3.78023622e+00  6.13780326e+00
  8.30540149e+00  1.02098724e+01  1.17910419e+01  1.29972950e+01
  1.37774249e+01  1.41319792e+01  1.40585758e+01  1.35636816e+01
  1.26345244e+01  1.13409083e+01  9.72216360e+00  7.79464305e+00
  5.64544223e+00  3.32503222e+00  8.88107041e-01 -1.59329248e+00
 -4.05992507e+00 -6.45313746e+00 -8.71327144e+00 -1.07900854e+01
 -1.26380653e+01 -1.42147006e+01 -1.54892299e+01 -1.64390858e+01
 -1.70351433e+01 -1.72938948e+01 -1.71685631e+01 -1.67219979e+01
 -1.59044166e+01 -1.47824153e+01 -1.33665280e+01 -1.16678134e+01
 -9.75246391e+00 -7.63091465e+00 -5.35345831e+00 -2.96905840e+00
 -5.09631905e-01  1.97507060e+00  4.44430515e+00  6.85344809e+00
  9.15903461e+00  1.13337844e+01  1.33467125e+01  1.51336120e+01
  1.66966787e+01  1.80162922e+01  1.90746708e+01  1.98127969e+01
  2.02634499e+01  2.04221761e+01  2.02877631e+01  1.98449702e+01
  1.90974465e+01  1.80799531e+01  1.68069397e+01  1.52959771e+01
  1.35665801e+01  1.16227312e+01  9.51601869e+00  7.27388893e+00
  4.92519240e+00  2.49981337e+00  2.82932820e-02 -2.45817963e+00
 -4.92460367e+00 -7.34030894e+00 -9.67635928e+00 -1.19050601e+01
 -1.40002645e+01 -1.59376556e+01 -1.76950019e+01 -1.92523833e+01
 -2.05923861e+01 -2.16995543e+01 -2.25478860e+01 -2.31432552e+01
 -2.34800725e+01 -2.35556687e+01 -2.33702741e+01 -2.29269662e+01
 -2.22315865e+01 -2.12926288e+01 -2.01211000e+01 -1.87303570e+01
 -1.71359212e+01 -1.53552740e+01 -1.34076356e+01 -1.13137308e+01
 -9.09554383e+00 -6.77606668e+00 -4.37904252e+00 -1.92870828e+00
  5.50461201e-01  3.03400451e+00  5.49771780e+00  7.91788934e+00
  1.02715222e+01  1.25365431e+01  1.46919953e+01  1.67182148e+01
  1.85969872e+01  2.03116866e+01  2.18473923e+01  2.31909872e+01
  2.43312337e+01  2.52588296e+01  2.59664444e+01  2.64391214e+01
  2.66748505e+01  2.66796333e+01  2.64545680e+01  2.60026765e+01
  2.53288265e+01  2.44396400e+01  2.33433894e+01  2.20498837e+01
  2.05703459e+01  1.89172843e+01  1.71043584e+01  1.51396391e+01
  1.30387952e+01  1.08294252e+01  8.52903617e+00  6.15551380e+00
  3.72697869e+00  1.26164946e+00 -1.22228693e+00 -3.70679651e+00
 -6.17014862e+00 -8.59028675e+00 -1.09516293e+01 -1.32379536e+01
 -1.54338179e+01 -1.75246263e+01 -1.94966815e+01 -2.13317519e+01
 -2.29952001e+01 -2.44987532e+01 -2.58335652e+01 -2.69919481e+01
 -2.79673583e+01 -2.87543764e+01 -2.93186910e+01 -2.96679958e+01
 -2.98181354e+01 -2.97693731e+01 -2.95229769e+01 -2.90811595e+01
 -2.84133854e+01 -2.75430665e+01 -2.64934034e+01 -2.52713717e+01
 -2.38845608e+01 -2.23353782e+01 -2.06051319e+01 -1.87442619e+01
 -1.67635423e+01 -1.46739620e+01 -1.24866789e+01 -1.01933401e+01
 -7.83474328e+00 -5.42495146e+00 -2.97607515e+00 -5.00072086e-01]

99. 给定一个整数n和一个二维数组X,从X中选择可以解释为从n度的多项分布中提取的行,即只包含整数且和为n的行

1
2
3
4
5
6
7
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print (X[M])
[[2. 0. 1. 1.]]

100. 对于一个一维数组X,计算它boostrapped之后的95%置信区间的平均值

1
2
3
4
5
6
X = np.random.randn(100) # random 1D array
N = 1000 # number of bootstrap samples
idx = np.random.randint(0, X.size, (N, X.size))
means = X[idx].mean(axis=1)
confint = np.percentile(means, [2.5, 97.5])
print (confint)
[-0.18822493  0.15997818]

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2021 朝着牛逼的道路一路狂奔 All Rights Reserved.

访客数 : | 访问量 :