numpy 中不常用的一些方法

作者:代码律动
链接:https://zhuanlan.zhihu.com/p/36303821
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

挑战 1:引入 numpy 并查看 numpy 的版本。

要求:这是第一步,以后我们使用 numpy 时都将用别名 np。

# 答案
import numpy as np print(np.__version__) #> 1.13.3 

挑战 2:创建数组

要求:创建一维数组,内容为从 0 到 9。

# 输入数组
arr = np.arange(10) 

挑战 3:创建布尔数组

要求:数组大小为 3*3,全部为 True。

# 答案一:
np.full((3, 3), True, dtype=bool) # 答案二: np.ones((3,3), dtype=bool) 

挑战 4:按要求抽取数组中的元素

要求:原数组为一维数组,内容为从 0 到 9,抽取出所有奇数。

扫描二维码关注公众号,回复: 2901294 查看本文章
# 输入数组
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 答案 arr[arr % 2 == 1] #> array([1, 3, 5, 7, 9]) 

挑战 5:按要求修改数组中的元素(原地修改)

要求:原数组为一维数组,内容为从 0 到 9,将所有奇数原地修改为 -1。

# 输入数组 
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 答案 arr[arr % 2 == 1] = -1 #> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1]) 

挑战 6:按要求修改数组中的元素(返回新数组)

要求:原数组为一维数组,内容为从 0 到 9,返回一个该数组的拷贝,其中奇数修改为 -1。

# 输入数组
arr = np.arange(10) # 答案 out = np.where(arr % 2 == 1, -1, arr) #> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1]) 

挑战 7:修改数组的形状

要求:将给定的一维数组 reshape 为二维数组,其中新数组的行数为2。

# 输入数组
arr = np.arange(10) # 答案 arr.reshape(2, -1) # -1 表示自动计算该维度的大小 #> array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) 

挑战 8:合并数组(列方向)

要求:将给定数组在列方向上合并。

# 输入数组
a = np.arange(10).reshape(2,-1) b = np.repeat(1, 10).reshape(2,-1) # 答案 1: np.concatenate([a, b], axis=0) # 答案 2: np.vstack([a, b]) # 答案 3: np.r_[a, b] #> array([[0, 1, 2, 3, 4], #> [5, 6, 7, 8, 9], #> [1, 1, 1, 1, 1], #> [1, 1, 1, 1, 1]]) 

挑战 9:合并数组(水平方向)

要求:将给定数组在水平方向上合并。

# 输入数组
a = np.arange(10).reshape(2,-1) b = np.repeat(1, 10).reshape(2,-1) # 答案 1: np.concatenate([a, b], axis=1) # 答案 2: np.hstack([a, b]) # 答案 3: np.c_[a, b] #> array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1], #> [5, 6, 7, 8, 9, 1, 1, 1, 1, 1]]) 

挑战 10:创建数组(进阶)

要求:不用硬编码,使用内置方法,从给定数组 a 生成数组 b。

# 输入数组
a = np.array([1,2,3]) b = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]) # 答案 np.r_[np.repeat(a, 3), np.tile(a, 3)] 

挑战 11:返回公共元素

要求:给定两个数组,要求返回这两个数组元素的交集。

# 输入数组
a = np.array([1,2,3,2,3,4,3,4,5,6]) b = np.array([7,2,10,2,7,4,9,4,9,8]) # 答案: np.intersect1d(a,b) #> array([2, 4]) 

挑战 12:删除元素

要求:给定两个数组 a、b,从数组 a 中删除 b 中出现的元素。

# 输入数组
a = np.array([1,2,3,4,5]) b = np.array([5,6,7,8,9]) # 答案 np.setdiff1d(a,b) #> array([1, 2, 3, 4]) 

挑战 13:找出相同元素

要求:给定两个数组 a、b,返回两数组中相同元素的下标。

# 输入数
a = np.array([1,2,3,2,3,4,3,4,5,6]) b = np.array([7,2,10,2,7,4,9,4,9,8]) # 答案: np.where(a == b) #> (array([1, 3, 5, 7]),) 

挑战 14:按要求取出元素

要求:从数组中取出大于等于 5 且小于等于 10 的元素。

# 输入数组
a = np.arange(15) # 答案 1: index = np.where((a >= 5) & (a <= 10)) a[index] # 答案 2: index = np.where(np.logical_and(a>=5, a<=10)) a[index] # 答案 3: a[(a >= 5) & (a <= 10)] #> (array([6, 9, 10]),) 

挑战 15:实现 max 的 numpy 版

要求:给定长度相同的数组 a、b,返回一个新数组,数组上的每一个元素为 max(a_i, b_i)。

若 pair_max 为满足要求的函数,则对于 a 和 b,期望输出如下:

# 输入数组
a = np.array([5, 7, 9, 8, 6, 4, 5]) b = np.array([6, 3, 4, 8, 9, 7, 1]) pair_max(a, b) #> 期望输出:array([ 6., 7., 9., 8., 9., 7., 5.]) # 答案: def maxx(x, y): """Get the maximum of two items""" if x >= y: return x else: return y pair_max = np.vectorize(maxx, otypes=[float]) a = np.array([5, 7, 9, 8, 6, 4, 5]) b = np.array([6, 3, 4, 8, 9, 7, 1]) pair_max(a, b) 

挑战 16:交换二维数组的列

要求:交换数组的第一第二列。

# 输入数组
arr = np.arange(9).reshape(3,3) # 答案: arr[:, [1,0,2]] #> array([[1, 0, 2], #> [4, 3, 5], #> [7, 6, 8]]) 

挑战 17:交换二维数组的行

要求:交换二维数组的第一第二行。

# 输入数组 
arr = np.arange(9).reshape(3,3) # 答案 arr[[1,0,2], :] #> array([[3, 4, 5], #> [0, 1, 2], #> [6, 7, 8]]) 

挑战 18:将一个数组按行反序

要求:数组 arr 为二维数组,将其行反序。

# 输入数组
arr = np.arange(9).reshape(3,3) # 答案: arr[::-1] 

挑战 19:将一个数组按列反序

要求:数组 arr 为二维数组,将其列反序。

# 输入数组
arr = np.arange(9).reshape(3,3) # 答案: arr[:, ::-1] 

挑战 20:创建随机数组

要求:创建一个 5*3 的数组,数组元素为 5 到 10 的随机浮点数。

# 答案 1: 
rand_arr = np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3)) # print(rand_arr) # 答案 2: rand_arr = np.random.uniform(5,10, size=(5,3)) print(rand_arr) #> [[ 8.50061025 9.10531502 6.85867783] #> [ 9.76262069 9.87717411 7.13466701] #> [ 7.48966403 8.33409158 6.16808631] #> [ 7.75010551 9.94535696 5.27373226] #> [ 8.0850361 5.56165518 7.31244004]] 

挑战 21:按要求打印数组(一)

要求:数组元素输出时保留 3 位小数。

# 输入数组 
rand_arr = np.random.random([5,3]) # 答案: # 设置保留 3 位小数 np.set_printoptions(precision=3) rand_arr[:4] #> array([[ 0.443, 0.109, 0.97 ], #> [ 0.388, 0.447, 0.191], #> [ 0.891, 0.474, 0.212], #> [ 0.609, 0.518, 0.403]]) 

挑战 22:按要求打印数组(二)

要求:数组为小数,使用小数点的形式来打印,而不是科学记数法(如1e-4)。

# 输入数组
np.random.seed(100) rand_arr = np.random.random([3,3])/1e3 rand_arr #> array([[ 5.434049e-04, 2.783694e-04, 4.245176e-04], #> [ 8.447761e-04, 4.718856e-06, 1.215691e-04], #> [ 6.707491e-04, 8.258528e-04, 1.367066e-04]]) # 答案: np.set_printoptions(suppress=True, precision=6) # precision 是可选项 rand_arr #> array([[ 0.000543, 0.000278, 0.000425], #> [ 0.000845, 0.000005, 0.000122], #> [ 0.000671, 0.000826, 0.000137]]) 

挑战 23:按要求打印数组(三)

要求:打印时省略中间元素,限制显示数组元素的个数为 6。

# 输入数组
a = np.arange(15) #> 原输出 :[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] #> 目标输出:[ 0 1 2 ..., 12 13 14] array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) # 答案: np.set_printoptions(threshold=6) a #> array([ 0, 1, 2, ..., 12, 13, 14]) 

挑战 24:加载特殊矩阵

要求:著名的 iris 数据集是包含兰花属性和种类的数据集,其中每行属性有数字和文字,用 numpy 来加载他们。

# 答案 
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris = np.genfromtxt(url, delimiter=',', dtype='object') names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species') # 输出前三行 iris[:3] #> array([[b'5.1', b'3.5', b'1.4', b'0.2', b'Iris-setosa'], #> [b'4.9', b'3.0', b'1.4', b'0.2', b'Iris-setosa'], #> [b'4.7', b'3.2', b'1.3', b'0.2', b'Iris-setosa']], dtype=object) 

挑战 25:重定义数组的元素范围

要求:将 iris 数组集的第一个列的数据范围缩放为 0 到 1。

# Input url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0]) # 答案 Smax, Smin = sepallength.max(), sepallength.min() S = (sepallength - Smin)/(Smax - Smin) # or S = (sepallength - Smin)/sepallength.ptp() print(S) #> [ 0.222 0.167 0.111 0.083 0.194 0.306 0.083 0.194 0.028 0.167 #> 0.306 0.139 0.139 0. 0.417 0.389 0.306 0.222 0.389 0.222 #> 0.306 0.222 0.083 0.222 0.139 0.194 0.194 0.25 0.25 0.111 #> 0.139 0.306 0.25 0.333 0.167 0.194 0.333 0.167 0.028 0.222 #> 0.194 0.056 0.028 0.194 0.222 0.139 0.222 0.083 0.278 0.194 #> 0.75 0.583 0.722 0.333 0.611 0.389 0.556 0.167 0.639 0.25 #> 0.194 0.444 0.472 0.5 0.361 0.667 0.361 0.417 0.528 0.361 #> 0.444 0.5 0.556 0.5 0.583 0.639 0.694 0.667 0.472 0.389 #> 0.333 0.333 0.417 0.472 0.306 0.472 0.667 0.556 0.361 0.333 #> 0.333 0.5 0.417 0.194 0.361 0.389 0.389 0.528 0.222 0.389 #> 0.556 0.417 0.778 0.556 0.611 0.917 0.167 0.833 0.667 0.806 #> 0.611 0.583 0.694 0.389 0.417 0.583 0.611 0.944 0.944 0.472 #> 0.722 0.361 0.944 0.556 0.667 0.806 0.528 0.5 0.583 0.806 #> 0.861 1. 0.583 0.556 0.5 0.944 0.556 0.583 0.472 0.722 #> 0.667 0.722 0.417 0.694 0.667 0.667 0.556 0.611 0.528 0.444] 

挑战 26:根据百分比大小返回元素

要求:返回数组中按从小到大排序,位置为 5% 和 95% 的数。

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0]) # 答案: np.percentile(sepallength, q=[5, 95]) #> array([ 4.6 , 7.255]) 

挑战 27:找出数组的缺失值

要求:数组中有多处缺失值(答案nan),找出他们的位置。

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3]) iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan # 答案: print("Number of missing values: \n", np.isnan(iris_2d[:, 0]).sum()) print("Position of missing values: \n", np.where(np.isnan(iris_2d[:, 0]))) #> Number of missing values: #> 5 #> Position of missing values: #> (array([ 39, 88, 99, 130, 147]),) 

挑战 28:数组缺失值判断

要求:返回数组是否具有缺失值。

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3]) iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan # 答案: np.isnan(iris_2d).any() #> False 

挑战 29:数组缺失值处理

要求:替换数组中的缺失值为0。

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3]) iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan # 答案 iris_2d[np.isnan(iris_2d)] = 0 iris_2d[:4] #> array([[ 5.1, 3.5, 1.4, 0. ], #> [ 4.9, 3. , 1.4, 0.2], #> [ 4.7, 3.2, 1.3, 0.2], #> [ 4.6, 3.1, 1.5, 0.2]]) 

挑战 30:数组的 unique 元素

要求:返回数组中出现的所有元素集合

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris = np.genfromtxt(url, delimiter=',', dtype='object') # 答案: species = np.array([row.tolist()[4] for row in iris]) np.unique(species, return_counts=True) #> (array([b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'], #> dtype='|S15'), array([50, 50, 50])) 

挑战 31:二维数组排序

要求:根据第一列排序二维数组

# 输入数组
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris = np.genfromtxt(url, delimiter=',', dtype='object') # 答案: print(iris[iris[:,0].argsort()][:5]) #> [[b'4.3' b'3.0' b'1.1' b'0.1' b'Iris-setosa'] #> [b'4.4' b'3.2' b'1.3' b'0.2' b'Iris-setosa'] #> [b'4.4' b'3.0' b'1.3' b'0.2' b'Iris-setosa'] #> [b'4.4' b'2.9' b'1.4' b'0.2' b'Iris-setosa'] #> [b'4.5' b'2.3' b'1.3' b'0.3' b'Iris-setosa'] 

挑战 32:出现最频繁的元素

要求:返回数组中出现最多的元素。

# 输入数组: 
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris = np.genfromtxt(url, delimiter=',', dtype='object') # 答案: vals, counts = np.unique(iris[:, 2], return_counts=True) print(vals[np.argmax(counts)]) #> b'1.5' 

挑战 33:找出数组中某元素满足第一次大于某数的下标

要求:在 iris 数据集中,返回第一个元素的下标,满足第4列属性大于1.0。

# 输入数组: 
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' 
iris = np.genfromtxt(url, delimiter=',', dtype='object') # 答案: np.argwhere(iris[:, 3].astype(float) > 1.0)[0] #> 50 

挑战 34:设定数组元素的上下限

要求:给定数组 a,将数组中大于 30 的数截断为 30,小于 10 的数截断为 10。

# 输入数组
np.set_printoptions(precision=2) np.random.seed(100) a = np.random.uniform(1,50, 20) # 答案 1: np.clip(a, a_min=10, a_max=30) # 答案 2: print(np.where(a < 10, 10, np.where(a > 30, 30, a))) #> [ 27.63 14.64 21.8 30. 10. 10. 30. 30. 10. 29.18 30. #> 11.25 10.08 10. 11.77 30. 30. 10. 30. 14.43] 

挑战 35:去掉所有缺失值

要求:给定一维数组 a 包含缺失值,去掉他们。

# 输入数组
a = np.array([1,2,3,np.nan,5,6,7,np.nan]) # 答案: a[~np.isnan(a)] #> array([ 1., 2., 3., 5., 6., 7.]) 

猜你喜欢

转载自www.cnblogs.com/onemorepoint/p/9541942.html