Numpy 100经典练习题前50题错题整理

吹灭读书灯,一身都是月。
  1. Print the numpy version and the configuration (★☆☆)
print(np.__version__)
np.show_config()
  1. How to find the memory size of any array(★☆☆)
Z = np,ones([10,10])
print("%d bytes" % (Z.size*Z.itemsize))

这里输出的是整个数组的内存大小,因此为 size x itemsize :(数组的大小和数组中单个元素类型的乘积)

  1. Reverse a vector (first element becomes last) (★☆☆)
Z = np.arange(1,10)
Z = Z[::-1]

此处实现数组的逆序,就可以利用切片的方法,[::-1]全选所有数组元素后再(-1)从倒数第一个数开始数起

  1. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
z = [1,2,0,0,4,0]
n = np.nonzero(z)
print(n)
  1. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
Z = np.random.random((10,10))
print(Z.max())
print(Z.min()) 
这道题并不难,但是我把它记录下来是因为我想做一个max和argmax的区分

假如现在有一个函数 : y = f(t)
max 等于 y 在t的范围内取得的最大值
argmax 等于 y 取最大值时候的 t 的值

  1. Create a 2d array with 1 on the border and 0 inside (★☆☆)
Z = np.ones([10,10])
Z[1:-1,1:-1]=0
  1. How to add a border (filled with 0’s) around an existing array? (★☆☆)
Z = np.ones((5,5))
Z = np.pad(Z,pad_width = 1, model = 'constant', constant_values = 0)

np.pad 函数的用法:
np.pad(array, pad_width, mode, *kwargs)
- array 为要填充的数组
- pad_width 是在各个维度的各个方向上想要填充的长度,如((1,2),(2,2)),表示在第一个维度上水平方向上padding=1,垂直方向上padding=2,在第二个维度上水平方向上padding=2,垂直方向上padding=2。如果直接输入一个整数,则说明各个维度和各个方向所填补的长度都一样。
- mode为填补类型,即怎样去填补,有“constant”,“edge”等模式,如果为constant模式,就得指定填补的值,如果不指定,则默认填充0。
- 剩下的都是一些可选参数

  1. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
Z = np.diag(np.arange(1,5),k=-1)
  1. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
Z =  np.ones((10,10))
Z[1::2,::2] = 0
Z[::2, 1::2] = 0

切片法 [1::2,::2] 逗号前面为对行操作,后面为对列操作

  1. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
print(np,unravel_index(100,(6,7,8)))

输出第100个元素在原始数组中的索引

  1. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
a = np.array([[1,0],
             [0,1]])
b = np.tile(a,(4,4))

利用np.tile函数扩张原数组来构造棋盘

  1. Normalize a 5x5 random matrix (★☆☆)
Z = np.random.random((5,5))
Z = (Z - np.mean(Z) / np.std(Z) )
  1. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)
color = np.dtype([('r', np.ubyte, 1),
				  ('g', np.ubyte, 1),
				  ('b', np.ubyte, 1),
				  ('a', np.ubyte, 1)])
  1. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
Z = np.ones((5,3)) @ np.ones((3,2))

这里的@是指两个数组的点积,同时也可以调用np.dot()来达到同样的效果
在这里插入图片描述

  1. What is the output of the following script? (★☆☆)
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))

这里的结果很有意思,
第一个print()输出9
第二个print()输出10

原因是因为python的sum函数的计算方式和numpy模块中的sum函数的计算机制不一样所导致。

  1. How to round away from zero a float array ? (★☆☆)
Z = np.random.uniform(-10,10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))

在这个操作中进行了三步;
第一步:使用abs取绝对值;
第二步:np.ceil的作用是对数取精度时四舍五入,整数取大于的(1.1 > 2),负数取小于的(-0.1 > -1 copysign(a,b)的作用是将b的符合赋给a
第三步:copysign是将原数组的符合拷贝过来

  1. Is the following expressions true? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)

结果为 : False

np.sqrt为在实数域中对-1开平方,输出为 nan

而np.emath.sqrt为在复数域中对-1开平方,输出为 1j

官方文档对np.emath的解释
注意 numpy.emath 是 numpy.lib.scimath 的首选别名, 在导入 numpy 后可用。 包装器函数对某些数学函数的调用更加用户友好,这些数学函数的输出数据类型与输入的某些域中的输入数据类型不同。 上面的例子很好解释了这句话
例如,对于带有分支切割的 log 之类的功能,此模块中的版本在复杂平面中提供数学上有效的答案:

  1. How to get all the dates corresponding to the month of July 2016? (★★☆)
Z = np.arange('2016-7', '2016-8', dtype = 'datetime64[D]')
print(Z)
  1. Extract the integer part of a random array using 5 different methods (★★☆)
Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
  1. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
def fun():
    for i in range(10):
        yield i
    
z = np.fromiter(fun(),dtype = int,count =  -1)
print(z)

这里的 yield 很有意思,起初我们可以将它看做 return 但是随着理解的深入发现,它并不是简单的return
解释:带yield的函数是一个生成器,而不是一个函数了,这个生成器有一个函数就是next函数,next就相当于“下一步”生成哪个数,这一次的next开始的地方是接着上一次的next停止的地方执行的,所以调用next的时候,生成器并不会从foo函数的开始执行,只是接着上一步停止的地方开始,然后遇到yield后,return出要生成的数,此步就结束。
解释的很清楚的一篇博客

  1. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
Z = np.linspace(0,1,11,endpoint=False)[1:]
print(Z)

numpy中的linspace函数多用于生成等差数组:

  • numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
  • start:返回样本数据开始点
  • stop:返回样本数据结束点
  • num:生成的样本数据量,默认为50
  • endpoint:True则包含stop;False则不包含stop
  • retstep:If True, return (samples, step), where step is the spacing between samples.(即如果为True则结果会给出数据间隔)
  • dtype:输出数组类型
  • axis:0(默认)或-1
  1. How to sum a small array faster than np.sum? (★★☆)
z = np.arange(10)
a = np.add.reduce(z)
print(a)

此处使用np的add函数,其效率高于np.sum

  1. Make an array immutable (read-only) (★★☆)
Z = np.ones(10)
Z.flags.weiteable = False
Z[1] = 0 

ValueError: assignment destination is read-only
我们发现报错,则此时数组Z只可读

  1. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

将直角坐标转变为极坐标:

Z = np.random.random(10,2)
X,Y = Z[:0],Z[:1]
P = np.sqrt(X**2 + Y**2)
A = np.arctan2(Y,X) 
  1. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)
Z = np.zeros((5,5),[('Z_x',float),('Z_y',float)])
Z['Z_x'],Z['Z_y'] = np.meshgrid(np.linspace(0,1,5),
                                np.linspace(0,1,5))

输出为:

[[(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.  )]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值