numpy练习

本文介绍了使用numpy进行版本检查、配置显示、数组操作、类型转换、信息获取、索引与重塑、非零值查找、矩阵运算、数据填充、形状操作、坐标变换、数组构造、数组比较、日期处理、随机数生成、数组统计、结构化数组、直角坐标转换、极坐标转换、数组优化及搜索最值等内容。
import numpy as np
print(np.__version__)
np.show_config()
1.19.1
blas_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\include']
blas_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\include']
lapack_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\include']
lapack_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['E:/ProgramData/Anaconda3/envs/tf2.3\\Library\\include']
Z = np.ones(10)
print(Z)
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
Z = np.zeros((10,10))
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.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
print("%d bytes" % (Z.size * Z.itemsize))
800 bytes
print("{}".format(Z.size * Z.itemsize))
800
Z.itemsize
8
np.info
<function numpy.info(object=None, maxwidth=76, output=<ipykernel.iostream.OutStream object at 0x0000021C2EE26AC8>, toplevel='numpy')>
Z = np.zeros(10)
Z[5] = 1
Z
array([0., 0., 0., 0., 0., 1., 0., 0., 0., 0.])
Z = np.arange(10,50)
Z
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
       27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
       44, 45, 46, 47, 48, 49])
Z = np.arange(9)
np.reshape(Z,(3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
(array([0, 1, 4], dtype=int64),)
Z = np.eye(3)
Z
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
np.random.random((3,3,3)).shape
(3, 3, 3)
Z = np.random.random((10,10))
np.max(Z),np.min(Z)
(0.9995614828372513, 0.008748034129026694)
Z = np.random.random(30)
Z.mean()
0.4525193349949122

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

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.]]
Z = np.ones((5,5))
np.pad(Z,pad_width = 2,mode='constant', constant_values=2)
array([[2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [2., 2., 1., 1., 1., 1., 1., 2., 2.],
       [2., 2., 1., 1., 1., 1., 1., 2., 2.],
       [2., 2., 1., 1., 1., 1., 1., 2., 2.],
       [2., 2., 1., 1., 1., 1., 1., 2., 2.],
       [2., 2., 1., 1., 1., 1., 1., 2., 2.],
       [2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [2., 2., 2., 2., 2., 2., 2., 2., 2.]])
0 * np.nan
nan
np.nan == np.nan
False
np.inf
inf
np.inf > np.nan
False
np.nan - np.nan
nan
0.3 == 3 * 0.1
False
3 * 0.1
0.30000000000000004

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

np.arange(4)
array([0, 1, 2, 3])
Z = np.diag(1+np.arange(4))
Z
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
Z = np.diag(1+np.arange(4),k=1) # K在主对角线上面,还是下面
Z
array([[0, 1, 0, 0, 0],
       [0, 0, 2, 0, 0],
       [0, 0, 0, 3, 0],
       [0, 0, 0, 0, 4],
       [0, 0, 0, 0, 0]])

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

Z = np.zeros((8,8),dtype=int)
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, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])
Z[1::2,::2] = 1
Z
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 1, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 1, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 1, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 1, 0, 1, 0]])
Z[::2,1::2] = 1
Z
array([[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)是什么?

Q = np.random.random((6,7,8))

unravel_index(indices, shape, order=‘C’)
indices 就是索引值,可以是一个数,也可以是一个列表。
例如 indices = 1 ,indices = [3,12] 。
shape 代表的是数组的形状
函数的作用就是得到 indices 中每一项对应到形状为shape的数组中的坐标。

print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)
np.unravel_index([22, 41, 37], (7,6))
(np.array([3, 6, 6]), np.array([4, 5, 1]))
np.unravel_index([31, 41, 13], (7,6), order='F')
(np.array([3, 6, 6]), np.array([4, 5, 1]))
(array([3, 6, 6]), array([4, 5, 1]))
a = [2,3,4,5,6,7,8,1,12,23,34,55]
b = np.array(a).reshape((3,4))
print(b)
[[ 2  3  4  5]
 [ 6  7  8  1]
 [12 23 34 55]]
np.unravel_index(7,(3,4),order="C")
(1, 3)

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

Z = np.tile( np.array([[0,1],[1,0]]), (3,3))
print(Z)
[[0 1 0 1 0 1]
 [1 0 1 0 1 0]
 [0 1 0 1 0 1]
 [1 0 1 0 1 0]
 [0 1 0 1 0 1]
 [1 0 1 0 1 0]]
a = [1, 2, 3]
b = np.tile(a, 2)
b
array([1, 2, 3, 1, 2, 3])
b = np.tile(a, 3)
b
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
Z = np.random.random((4,5))
Z
array([[0.40190652, 0.30602045, 0.78660736, 0.79006286, 0.46857736],
       [0.73928607, 0.25034014, 0.78878815, 0.9053959 , 0.44941201],
       [0.53044218, 0.13904618, 0.95918547, 0.98779074, 0.27377363],
       [0.84429444, 0.24627403, 0.09384873, 0.18253855, 0.63075715]])
Z.max(-1)
array([0.79006286, 0.9053959 , 0.98779074, 0.84429444])
color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
color
E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\ipykernel_launcher.py:4: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  after removing the cwd from sys.path.





dtype([('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')])
Z1 = np.random.random((5,3))
Z2 = np.random.random((3,2))
Z1,Z2
(array([[0.20547996, 0.3273501 , 0.15984982],
        [0.09920915, 0.60710609, 0.09866898],
        [0.90849081, 0.94514143, 0.25371245],
        [0.61277969, 0.63544792, 0.08197526],
        [0.12803159, 0.01340407, 0.69079278]]),
 array([[0.86560206, 0.18972041],
        [0.85147056, 0.63382571],
        [0.78857142, 0.21271258]]))
Z1@Z2
array([[0.58264585, 0.28046872],
       [0.68061615, 0.42460959],
       [1.79122201, 0.82538202],
       [1.13613191, 0.53645722],
       [0.66697702, 0.17972637]])

给定一个一维数组,对其在3到8之间的所有元素取反 (★☆☆)

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]
Z = np.arange(5)
Z ** Z  # legal
array([  1,   1,   4,  27, 256], dtype=int32)
print(np.array(0) // np.array(0))
0


E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in floor_divide
  """Entry point for launching an IPython kernel.
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
[1 2 5 9]
Z1,Z2
(array([3, 1, 2, 5, 7, 2, 5, 1, 2, 9]), array([8, 6, 2, 0, 5, 0, 2, 9, 8, 1]))
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 2020-10-05
Today is 2020-10-06
Tomorrow is 2020-10-07

np.datetime64(‘today’, ‘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']
## 提取随机数的整数部分
Z = np.random.uniform(0,10,10)
Z
array([0.16810903, 9.59121764, 7.71395414, 7.21803664, 7.69366273,
       6.9222278 , 4.06226357, 6.49995964, 9.59689444, 9.34069033])
print (np.floor(Z))
[0. 9. 7. 7. 7. 6. 4. 6. 9. 9.]
print (np.ceil(Z)-1)
[0. 9. 7. 7. 7. 6. 4. 6. 9. 9.]
np.ceil(Z)
array([ 1., 10.,  8.,  8.,  8.,  7.,  5.,  7., 10., 10.])
Z = np.linspace(0,10,10,endpoint=False)[1:]
print (Z)
[1. 2. 3. 4. 5. 6. 7. 8. 9.]
Z = np.arange(10)
np.add.reduce(Z)
45
sum(Z)
45
X = np.arange(8).reshape((2,2,2))
X
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])
sum(X)
array([[ 4,  6],
       [ 8, 10]])
np.add.reduce(X)
array([[ 4,  6],
       [ 8, 10]])
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) # 比较两个array是不是每一元素都相等
print(equal)
False
equal = np.array_equal(A,B)
print(equal)
False

直角坐标转化为极坐标

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.72628514 0.72675508 0.72716821 0.7558053  1.01990372 0.72662107
 0.9731911  1.30019838 0.73533109 0.69792346]
[0.4138511  1.26658697 0.63877982 0.20687776 0.35887851 1.34449106
 0.05132117 0.80118363 0.78778002 0.30213957]

两者输入不同, arctan仅仅输入正切值,arctan2要输入对边和直角边的具体数值,用来确定象限
两者的值域不同,arctan的值域是[ − π 2 , π 2 ] [-\frac{\pi}{2}, \frac{\pi}{2}][−
2
π

,
2
π

], arctan2的值域是[ − π , π ] [-\pi, \pi][−π,π]

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

Z = np.random.random(10)
print (Z)
[0.56945164 0.71671363 0.87783409 0.64726814 0.61884474 0.11584415
 0.20293375 0.64979239 0.11855371 0.70896716]
Z.argmax()
2
Z[Z.argmax()] = 0
print (Z)
[0.56945164 0.71671363 0.         0.64726814 0.61884474 0.11584415
 0.20293375 0.64979239 0.11855371 0.70896716]

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

Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
                             np.linspace(0,1,5))
print(Z)
[[(0.  , 0.  ) (0.25, 0.  ) (0.5 , 0.  ) (0.75, 0.  ) (1.  , 0.  )]
 [(0.  , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1.  , 0.25)]
 [(0.  , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1.  , 0.5 )]
 [(0.  , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1.  , 0.75)]
 [(0.  , 1.  ) (0.25, 1.  ) (0.5 , 1.  ) (0.75, 1.  ) (1.  , 1.  )]]
np.linspace(0,1,5) # 返回几个数
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
np.linspace(0,1,5,retstep=True) 
(array([0.  , 0.25, 0.5 , 0.75, 1.  ]), 0.25)
np.linspace(0,1,5,endpoint=False) 
array([0. , 0.2, 0.4, 0.6, 0.8])
np.arange(0,10,1)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.1636371179666
X,Y
(array([0, 1, 2, 3, 4, 5, 6, 7]),
 array([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]))
np.subtract.outer(X, X) ##B中的每个元素减去A中每个元素的值
array([[ 0, -1, -2, -3, -4, -5, -6, -7],
       [ 1,  0, -1, -2, -3, -4, -5, -6],
       [ 2,  1,  0, -1, -2, -3, -4, -5],
       [ 3,  2,  1,  0, -1, -2, -3, -4],
       [ 4,  3,  2,  1,  0, -1, -2, -3],
       [ 5,  4,  3,  2,  1,  0, -1, -2],
       [ 6,  5,  4,  3,  2,  1,  0, -1],
       [ 7,  6,  5,  4,  3,  2,  1,  0]])

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

Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print (Z[index])
6
Z,v
(array([ 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]),
 6.059749238050916)
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.))]


E:\ProgramData\Anaconda3\envs\tf2.3\lib\site-packages\ipykernel_launcher.py:5: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  """

### NumPy 练习题及答案 #### 打印当前 Numpy 版本 为了确认安装的 NumPy 库版本,可以使用如下代码: ```python import numpy as np print(np.__version__) ``` 这段代码会输出当前环境中所使用的 NumPy 的具体版本号[^1]。 #### 获取特定范围内的数组元素 对于获取一个一维数组中满足条件的子集操作,可以通过布尔索引来实现。下面的例子展示了如何选取介于5到10之间的数值(包括边界值): ```python array = np.arange(15) nums = array[(array >= 5) & (array <= 10)] ``` 这里创建一个包含从0至14共15个连续整数的一维数组从中筛选出了大于等于5且小于等于10的所有元素[^2]。 #### 在二维数组中随机放置指定数量的元素 当需要在一个已知大小的二维矩阵里随机分布若干个相同或不同的值时,可采用以下函数来完成这一任务: ```python def place_elements_randomly(shape, p, value=1): ''' 在给定形状的2D数组中随机放置p个元素,默认为1 参数说明: shape: 一个元组,指定了2D数组的尺寸; p: 整数,表示要放置的元素数目; value: 要填充的目标值,缺省情况下设为1. 返回值: 修改过的2D数组对象. ''' arr = np.zeros(shape, dtype=int) all_positions = np.arange(arr.size) chosen_positions = np.random.choice(all_positions, p, replace=False) np.put(arr, chosen_positions, value) return arr ``` 此方法接收三个参数:目标数组的维度`shape`,待插入项的数量`p`以及这些项目的实际取值`value`(如果未特别指出则默认设置成1),最终返回经过更新处理的新版二维数组实例[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值