一个关于numpy的题库GitHub-Numpy100题,原文中 vector 解释为行向量(代码中使用 vector),matrix 解释为矩阵或数组(代码中使用 a 或 array),原作者对于 array 的使用在两种释义中切换,所以这个就看情况吧()。
#### 1. Import the numpy package under the name "np" (★☆☆)
import numpy as np
#### 2. Print the numpy version and the configuration (★☆☆)
print(np.__version__)
np.show_config()
#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)
np.info(np.function) #np.function为 numpy 的指令
#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)
print(np.array(0) / np.array(0)) # 会有如下warning ↓
##RuntimeWarning: invalid value encountered in true_divide print(np.array(0) / np.array(0))
defaults = np.seterr(all="ignore") # 加上这句就没了
print(np.array(0) / np.array(0))
#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
print(np.iinfo(np.int64))
print(np.iinfo(np.int32))
print(np.iinfo(np.uint16))
print(np.finfo(np.float64))
print(np.finfo(np.float16))
# 结果
Machine parameters for int64
---------------------------------------------------------------
min = -9223372036854775808
max = 9223372036854775807
---------------------------------------------------------------
Machine parameters for int32
---------------------------------------------------------------
min = -2147483648
max = 2147483647
---------------------------------------------------------------
Machine parameters for uint16
---------------------------------------------------------------
min = 0
max = 65535
---------------------------------------------------------------
Machine parameters for float64
---------------------------------------------------------------
precision = 15 resolution = 1.0000000000000001e-15
machep = -52 eps = 2.2204460492503131e-16
negep = -53 epsneg = 1.1102230246251565e-16
minexp = -1022 tiny = 2.2250738585072014e-308
maxexp = 1024 max = 1.7976931348623157e+308
nexp = 11 min = -max
---------------------------------------------------------------
Machine parameters for float16
---------------------------------------------------------------
precision = 3 resolution = 1.00040e-03
machep = -10 eps = 9.76562e-04
negep = -11 epsneg = 4.88281e-04
minexp = -14 tiny = 6.10352e-05
maxexp = 16 max = 6.55040e+04
nexp = 5 min = -max
---------------------------------------------------------------
#### 49. How to print all the values of an array? (★★☆)
print(np.eye(10))
np.set_printoptions(threshold=10) # threshold调整显示最大值
print(np.eye(10))
#结果
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
[[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. 1. 0.]
[0. 0. 0. ... 0. 0. 1.]]
指令 | 功能 |
---|---|
np.empty(shape[, dtype]) | 创建一个大小为shape的随机数组(未初始化) |
np.zeros(shape) | 创建一个全0数组 |
np.ones(shape) | 创建一个全1数组 |
np.eye(size) | 创建一个 size*size 的单位矩阵 |
np.full(shape,value) | 创建一个由value填满,大小为shape的数组 |
np.random.random(shape) | 创建一个由随机数填充的矩阵 |
np.array() | 用标准库array生成 |
np.arange(a,b[,c]) | 创建一个从a到b(不包含b),步长为c的行向量 |
np.linspace(a, b[, c, endpoint=True, retstep=False, dtype=None]) | 从a到b均匀选取c个值创建一个行向量,c默认为50,Endpoint取舍末端值,retstep展示步长 |
#例子
a1 = np.full((4,3),1) #创建4行3列由1填充的矩阵(数组)
a2 = np.full_like(a1,3) #创建一个与vector1相同但由3填充的矩阵(数组)
#### 3. Create a null vector of size 10 (★☆☆)
#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
null_vector = np.zeros(10)
null_vector[4] = 1
#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)
vector = np.arange(10,50)
#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
a = np.arange(9).reshape((3, 3))
# or
a = np.arange(9)
np.reshape(a, (3,3))
#### 11. Create a 3x3 identity matrix (★☆☆)
a = np.eye(3)
#### 12. Create a 3x3x3 array with random values (★☆☆)
a = np.random.random((3,3,3))
#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
a = np.eye(2)
print(np.tile(a,(4,4)))
np.tile
可以用于复制平移某一个矩阵,具体请自行查询
#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
print(np.tile(np.arange(5), (5, 1)))
#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
不太会捏,让俺再想想吧
#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
print(np.linspace(0, 1, 11, endpoint = False)[1:])
#因为不包含首尾,所以用np.arange有点麻烦,还得自己算间隔(11等分有点难顶)
#### 40. Create a random vector of size 10 and sort it (★★☆)
a = np.random.uniform(0,10,10)
a.sort()
print(a)
#### 59. How to sort an array by the nth column? (★★☆)
#### 46. Create a structured array with 'x' and 'y' coordinates covering the [0,1]x[0,1] area (★★☆)
这个题有点像 MATLAB 里面生成一个 meshgrid 一样:
# 1
x = y = int(input('a number: '))
xx, yy = np.meshgrid(np.linspace(0,1,x), np.linspace(0,1,y))
xy = np.stack((xx,yy),axis=2) # 也可以用np.dstack(),就不需要axis=2这个参数了
print(xy)
# 2
a = np.zeros((x,y),[('x',np.float),('y',np.float)])
a['x'],a['y'] = np.meshgrid(np.linspace(0,1,x),np.linspace(0,1,y))
print('\n\n',a)
# 结果
a number: 3
[[[0. 0. ]
[0.5 0. ]
[1. 0. ]]
[[0. 0.5]
[0.5 0.5]
[1. 0.5]]
[[0. 1. ]
[0.5 1. ]
[1. 1. ]]]
[[(0. , 0. ) (0.5, 0. ) (1. , 0. )]
[(0. , 0.5) (0.5, 0.5) (1. , 0.5)]
[(0. , 1. ) (0.5, 1. ) (1. , 1. )]]
其中法2的a中元素的类型不是tuple
,而是
。实际上为了方便索引和后续处理,第一种方法要更好一些。
如果单纯想将两个行向量组成类似坐标的形式,也可以这么做:
vector1 = np.arange(3)
vector2 = np.arange(5,8)
print(np.concatenate((vector1[None],vector2[None]),axis=0).T)
print(np.column_stack((vector1,vector2)))
# 结果
[[0 5]
[1 6]
[2 7]]
#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
# 开始套娃
mydtype = np.dtype([('xy',[('x', np.int64), ('y', np.int64)]), ('rgb',[('r', np.int16), ('g', np.int16), ('b', np.int16)])])
print(np.ones((3, 2), mydtype))
#### 54. How to read the following file? (★★☆)
1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
from io import StringIO
s = StringIO("""1, 2, 3, 4, 5\n
6, , , 7, 8\n
, , 9,10,11\n""")
print(np.genfromtxt(s,delimiter=','))
#### 57. How to randomly place p elements in a 2D array? (★★☆)
a = np.zeros((5,6))
p_num = int(input()) # 要插入的p的个数,因为这里要用来生成一个
# 插入矩阵所以提前输入了这个;实际中如果
# 已经有了p的矩阵,可以直接用 p.size 代替
p = np.random.random(p_num)
np.put(a,np.random.choice(a.size,p_num,replace=False),p)
# np.put(a, ind, v[, mode=''])用数组v中
# 的值替换数组a中索引为 ind 的元素,ind可
# 以是一切合法的索引形式,包括布尔值的索引;
# v也可以是多维的,如下被注释掉的一行
#np.put(a,np.random.choice(a.size,p_num,replace=False),p.reshape(2,int(p_num/2)))
# choice(a, size=None, replace=True, p=None)
# 用来随机抽取,replace=False意味着没有重复
print(a)
print(np.array(a.nonzero())[0,:].size) # 用来检测是否将p全部插入
# 结果
10
[[0.91023252 0.67975792 0. 0. 0. 0.95960602]
[0. 0. 0. 0. 0.37070113 0.34431715]
[0.6080532 0. 0. 0. 0.72130095 0. ]
[0. 0.30608934 0.74424351 0.29370978 0. 0. ]
[0. 0. 0. 0. 0. 0. ]]
10
上题np.random.choice
参数如下:
Generates a random sample from a given 1-D array
Parameters
----------
a : 1-D array-like or int
If an ndarray, a random sample is generated from its elements.
If an int, the random sample is generated as if a were np.arange(a)
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
replace : boolean, optional
Whether the sample is with or without replacement
p : 1-D array-like, optional
The probabilities associated with each entry in a.
If not given the sample assumes a uniform distribution over all
entries in a.
Returns
-------
samples : single item or ndarray
The generated random samples
ndarray 的简单索引:
a = np.random.random(7,6)
print(a[1]) # 矩阵第二行
print(a[1][-1])
print(a[1, -1]) # 矩阵第二行倒数第一列的数据,以上两种方式均可;但是第一种方法
# 实际上耗时高于第二种,因为它是先创建一个临时索引组 a[1] ,然
# 后在其中索引倒数第一个值,而非直接索引
print(a[1,:]) # 矩阵第二行,输出仍为 numpy.ndarray
print(a[:,1]) # 矩阵第二列,输出仍为 numpy.ndarray,是行向量而非(4,1)的数组
print(a[1:3,1]) # 矩阵第二列第二至三行的数据;在 x:y 中不包含 y;不填写x/y默认
# 索引到首/尾,y 可以超过最大行/列索引,但只会输出到末尾值
print(a[:,1:3]) # 矩阵第二至第三列的所有行
print(a[::2,:]) # 矩阵奇数行,切片格式为 start:stop:step,与元组完全相同
print(a[1:6:2]) # 矩阵第二到第六行,间隔为2(第二、四、六行,总共三行)
print(a[np.array([[1,1],[2,3]])]) # 也可以利用 narray 来进行索引
#### 8. Reverse a vector (first element becomes last) (★☆☆)
# 可以直接应用 Python 的切片进行行向量的颠倒(而非转置)
# list[start:stop:step], step 为负则从后向前索引,list
# 为列表、字符串或者是这里的 numpy.ndarray 等
print(np.arange(5))
print(np.arange(5)[::-1])
# 也可以对数组进行这种操作,但最终仅是列向量的颠倒
a = np.arange(15).reshape((5, 3))
print(a,'\n\n',a[::-1])
#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)
a = np.ones((6,6))
a[1:-1,1:-1] = 0
print(a)
#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
# 有关奇偶位置切片的问题
a = np.zeros((8, 8))
a[::2, ::2] = 1
a[1::2, 1::2] = 1
print(a)
#### 20. 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)))
np.unravel_index
是一个获取某种矩阵特定位置/顺序的索引的函数,非常方便(尤其对于(x1,x2,x3,…)这种变态 shape)。有关 np.unravel_index
的讲解可以查看这篇博客(https://blog.csdn.net/kai123wen/article/details/98851946)
#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)
a = np.random.randint(0, 9, 10)
a[(a >= 3) & (a <= 8)] *= -1
print(a)
这里使用到了布尔索引(有空再研究)
#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
a = np.random.uniform(0,10,10)
a[a.argmax()] = 0
#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
(枚举法给出数组的等价形式?
a = np.arange(24).reshape((2,3,4))
for index, x in np.ndenumerate(a):
print(index,x) # index 的类型为 tuple
#### 4. How to find the memory size of any array (★☆☆)
a1 = np.empty((3, 2), np.uint32)
a2 = np.empty((3, 2), np.float64)
print(a1.itemsize * a1.size)
print(a2.itemsize * a2.size)
指令 | 功能 |
---|---|
ndarray.ndim | 数组的秩 |
ndarray.shape | 数组的维度 |
ndarray.size | 数组的元素总个数(大小) |
ndarray.dtype | 数组中元素类型 |
ndarray.itemsize | 数组中每个元素的字节大小 |
#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
print(np.nonzero([1, 2, 0, 0, 4, 0]))
# np.nonzero 的功能如下
>>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
[0, 4, 0],
[5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))
>>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 0],
[2, 1]])
#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
a = np.random.random((10,10))
print(a.max(),a.min()) # 也可以使用 np.max(a)
#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)
a1 = np.random.random((4,5))
a2 = np.pad(a, 1, pad_with, padder=0)
print(a2)
# np.pad 还有其他用法,可以自己用 np.info 查看一下(其实是我懒得看了,以后再更)
# 这个题也可以复杂一些:
a1 = np.zeros((2,3))
a2 = np.ones(tuple(map(sum,zip(a1.shape,(2,2))))) # 因为元组中各个元素不能直接相加
# 如(3,4)+(1,1)所得为(3,4,1,1),因此只能用这样
# 一个复杂的步骤
a2[1:-1,1:-1] = a1 # 类似于第15题
print(a2)
#### 17. What is the result of the following expression? (★☆☆)
# 这个题自己 print 就行
0 * np.nan # nan
np.nan == np.nan # False
np.inf > np.nan # False
np.nan - np.nan # nan
np.nan in set([np.nan]) # True
0.3 == 3 * 0.1 # False
# 浮点数可以比大小但是不能判断相等
# 需要其他方法进行相等判断
#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
print(np.diag([1, 2, 3, 4], -1))
# np.diag 的一些解释
Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal. # 这一条既是本题解决方法
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
Z**Z # legal,结果为Z^(Z),对每个元素broad
2 << Z >> 2 # legal,但是不太清楚是啥运算
Z <- Z # legal,但print出来是对Z < -Z的判断,看来和空格位置无关(长的像R的赋值一样)
1j*Z # legal,复数运算
Z/1/1 # legal
Z<Z>Z # illegal,也不清楚这是要干啥
#### 28. What are the result of the following expressions? (★☆☆)
np.array(0) / np.array(0) # nan,但是会warning,除法运算(float)
np.array(0) // np.array(0) # 0,同样会warning,除法运算(int)
np.array([np.nan]).astype(int).astype(float) # [-2.14748365e+09]
#### 29. How to round away from zero a float array ? (★☆☆)
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
取整问题
a =np.random.uniform(-10, 10, 10)
print(a)
print(np.round(a)) # 四舍五入, 但是0.5奇进偶不进
print(np.ceil(a)) # 天花板函数,向上取整
print(np.floor(a)) # 地板函数,向下取整
print(np.rint(a)) # 四舍五入
print(np.trunc(a)) # 截断,保留整数部分
print(np.modf(a)) # 把整数和小数分开,返回一个元组,第一个元素为
# 小数部分的narray,第二个为整数部分的narray
print(a.astype(int)) # 截断,保留整数部分
print(a-a%1) # 模1得小数部分,类似截断
print(np.floor(a[a > 0])) # 36题答案,按照正数的特性换用取整函数即可
#### 30. How to find common values between two arrays? (★☆☆)
print(np.intersect1d([1, 2, 3, 4, 5], [7, 6, 5, 4])) # 不会考虑相同元素的顺序
a1 = np.array([i for i in range(8)]).reshape((4,2))
a2 = np.array([7-i for i in range(8)]).reshape((2,4))
print(a1, '\n\n', a2, '\n\n', np.intersect1d(a1, a2)) # 也不考虑矩阵大小
#### 32. Is the following expressions true? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)
print(np.sqrt(-1) == np.emath.sqrt(-1))
False
print(np.sqrt(-1)) # 在实数域,结果是nan
print(np.emath.sqrt(-1)) # 在复数域开根,结果是1j
#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
A = np.random.uniform(0,10,(2,4))
B = np.random.uniform(0,10,(2,4))
print((A+B)*(-A/2)) # 这样相当于又创建了多个临时区域来储存结果
np.add(A,B,out=B) # out=B 就将结果覆盖了原来的B
#print(B) 此时B已经是A+B了,且直接输出给了B,没有新建区域来储存A+B
np.divide(A,2,out=A)
np.negative(A,out=A)
print(np.multiply(A, B, out=A))
有关 numpy 中的拷贝可以参考这里
#### 43. Make an array immutable (read-only) (★★☆)
a = np.zeros((5,2))
print(a.flags)
# array的基本属性
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True # 是否可以写入
ALIGNED : True # 是否对齐
WRITEBACKIFCOPY : False # 强拷贝后能否通过写入拷贝改写原array
UPDATEIFCOPY : False # 强拷贝后能否通过更新拷贝改写原array
# 本题解答:
a.flags.writeable = False
a[0] = 1
#报错:
ValueError: assignment destination is read-only
函数名 | 简写或解释 | 函数名 | 简写或解释 |
---|---|---|---|
np.add(x,y) | x+y (broad) | np.mod(x,y) | 取模 |
np.subtract(x,y) | x-y | np.power(x,y) | x**y(broad的元素乘方) |
np.multiply(x,y) | x*y(broad的元素相乘) | np.dot(x,y) | x@y(XYT) |
np.cross(x,y) | 向量叉乘(broad的行向量叉乘) | np.outer(x,y) | XTY |
a.conj() | a 的共轭 | a.transpose() | a.T(a 的转置) |
np.divide(x,y) | x/y (broad) | np.sqrt(x) | √x (broad) |
其中有关乘法运算给出几个例子:
# example 1
a1 = np.array([1,0,0])
a2 = np.array([0,1,0])
print(np.multiply(a1,a2),' ',np.dot(a1,a2),' ',np.cross(a1,a2),'\n\n',np.outer(a1,a2))
# example 2
a3 = np.array([[1,0,0],[0,1,0]])
a4 = np.array([[0,1,0],[1,0,0]])
print(np.multiply(a3,a4),'\n\n',np.cross(a3,a4))
# 输出结果如下
[0 0 0] 0 [0 0 1]
[[0 1 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]]
[[ 0 0 1]
[ 0 0 -1]]
以下是关于np.add()
的一些说明,其他简单运算函数的参数大体相同:
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.
#### 14. Create a random vector of size 30 and find the mean value (★☆☆)
a = np.random.random(30)
print(a.mean())
# 更快一点
print(np.mean(np.random.random(30)))
#### 22. Normalize a 5x5 random matrix (★☆☆)
不太清楚他这里的 Normalize 是想怎么处理,看了看别人的也五花八门,就随便写了几个:array.std()
计算数组方差,a.mean()
计算数组平均数(均是对数组内所有元素进行统计,而不是分行或者分列)
a = np.random.random((6,5))
print(a / np.sqrt(a.size * (np.power(a.mean(),2) + np.power(a.std(),2)))) # 除以几何平均值
print((a - a.mean()) / a.std()) # 高斯分布的归一化
#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
a1 = np.full((5,3),1)
a2 = np.full((3,2),2)
print(a1 @ a2)
print(np.dot(a1, a2))
#### 26. What is the output of the following script? (★☆☆)
# Author: Jake VanderPlas
print(sum(range(5),-1)) # 9 = 0+1+2+3+4+(-1)
from numpy import *
print(sum(range(5),-1)) # 10
这道题实际上是指出了Python内置sum()
函数和np.sum()
的区别
sum(iterable[, start]) # Python内置,iterable为可迭代对象,如:列表、元组、集合;
# start为前者总和后再加上的参数值
np.sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)
# 题目中所输入的-1等价于 axis=-1,一维数组就是 axis=0,所以
# 上题就是直接按行求和;对于二维数组和 axis=1 相同(倒数第一
# 个),那就是按列求和,最终输出一个行向量
#### 41. How to sum a small array faster than np.sum? (★★☆)
import time
a = np.arange(20)
start1 = time.perf_counter()
print(a.sum())
end1 = time.perf_counter()
print('Running time: %s Seconds'%(end1-start1))
start2 = time.perf_counter()
print(np.add.reduce(a))
end2 = time.perf_counter()
print('Running time: %s Seconds'%(end2-start2))
# 结果
190
Running time: 3.469999999999862e-05 Seconds
190
Running time: 9.700000000001374e-06 Seconds
np.sum()
和np.add.reduce()
在功能上没有任何区别。但是这种方法仅适用于行向量,因为np.sum()
默认是求所有元素之和,而np.add.reduce()
和np.add()
一样由 axis=0 的默认设置,所以对于矩阵或数组来说需要进一步设置一下。如下:
import time
a = np.arange(20).reshape((4,5))
print(a.sum())
print(np.sum(a, axis=0))
print(np.add.reduce(a,axis=(0,1)))
print(np.add.reduce(a))
#结果
190
[30 34 38 42 46]
190
[30 34 38 42 46]
#### 42. Consider two random array A and B, check if they are equal (★★☆)
a1 = np.random.uniform(0,10,5)
a2 = np.random.uniform(0,10,5)
print(a1 == a2) # 判断每个对应位置的元素是否相同,输出为 ndarray
print(np.allclose(a1,a2)) # Returns True if two arrays are element-wise equal within a tolerance.
print(np.array_equal(a1,a2)) # True if two arrays have the same shape and elements, False otherwise.
# 后两种方法均是返回单个布尔值
#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
a = np.random.uniform(-10,10,(10,2))
#1 np.column_stack可以按列合并矩阵或向量;该法实际上是有一定问题的,后说
a_polar = np.column_stack((np.sqrt(np.add.reduce(np.square(a), axis=1)), np.arctan(np.divide.reduce(a, axis=1))))
#2 也可以先创建一个和原矩阵相同大小的储区
a_polar = np.zeros_like(a)
a_polar[:,0] = np.sqrt(np.square(a[:,0]) + np.square(a[:,1]))
a_polar[:,1] = np.arctan2(a[:,1],a[:,0])
需要注意的是np.arctan
仅接受单个数组作为正弦值输入,返回范围在[−π/2, π/2];而np.arctan2
接受两个数组(或向量)作为输入(前者作为分子或对边,后者作为分母或邻边),当然他们必须是可以 broad 的,并且最终返回值的范围是 [−π, π],因为你可以根据两个值判断象限。所以上题中第一种方法用np.arctan(np.divide.reduce(a, axis=1))
是不正确的,因为极坐标θ显然是 (−π, π] 的,还是得换成np.arctan2(a[:,1],a[:,0])
。
#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
X = np.arange(6,10)
Y = np.arange(1,5)
# 1 暴力解题
xx, yy = np.size(X),np.size(Y)
C = np.zeros((xx,yy))
for i in range(xx):
for j in range(yy):
C[i,j] = 1/(X[i]-Y[j])
print(C,'\n')
# 2 numpy的人性化方法
C = 1.0 / np.subtract.outer(X, Y)
print(C)
# 结果,两个一样(显示是这样的)
[[0.2 0.25 0.33333333 0.5 ]
[0.16666667 0.2 0.25 0.33333333]
[0.14285714 0.16666667 0.2 0.25 ]
[0.125 0.14285714 0.16666667 0.2 ]]
#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
a = np.random.random((100,2))
X,Y = np.atleast_2d(a[:,0], a[:,1])
Dist = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(Dist)
# 需要注意的是单纯将X赋为a的第一列索引,所得为行向量
X2 = a[:,0]
print(X2)
# 而使用np.atleast_2d可以确保赋值所得至少为二维矩阵
print(X)
#### 56. Generate a generic 2D Gaussian-like array (★★☆)
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)))
#### 58. Subtract the mean of each row of a matrix (★★☆)
a = np.random.uniform(-10,10,(4,5))
# print(np.mean(a,axis=1,keepdims=True))
a = np.subtract(a,np.mean(a,axis=1,keepdims=True))
print(a)
#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)
有关numpy的数据类型(dtype)可以参考这里
print(np.dtype([('R', np.int32), ('G', np.int32), ('B', np.int32), ('A', np.int32)]))
numpy.datetime64
是 numpy 用来储存日期的类型,你可以把他看成按年-月-日进制的数据(逢30/31日进1月哈哈哈)
#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(type(today),today,tomorrow)
<class 'numpy.datetime64'> 2022-11-09 2022-11-10 # 结果如左
#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)
July = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(July)
#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?
a = np.empty((5,2),dtype=np.float32)
print(np.dtype(a[0,0]))
a = a.astype(np.int32,copy=False)
print(np.dtype(a[0,0]))
np.astype
用于更改数组内元素类型,但仅在赋值语句中能发挥真正作用(单纯键入a.astype(np.int32,copy=False)
没有任何实际效应)