1 # coding: utf-8 2 3 # 通用函数:快速的逐元素数组函数 4 5 # 通用函数,也可以称为ufunc,是一种在ndarray数据中进行逐元素操作的函数 6 import numpy as np 7 arr = np.arange(10) 8 arr 9 10 # 简单的逐元素转换,sqrt,exp函数,为一元通用函数 11 # sqrt,开根号 12 np.sqrt(arr) 13 14 #exp函数 15 np.exp(arr) 16 17 # 二元通用函数,比如add,maximum接收两个数组并返回一个数组的结果 18 x = np.random.randn(8) 19 x 20 y = np.random.randn(8) 21 y 22 23 # 逐个元素地将x和y中元素地最大值计算出来 24 np.maximum(x, y) 25 26 # 返回多个数组的通用函数,如modf,返回浮点值数组的小数部分和整数部分 27 arr = np.random.randn(7)*5 28 arr 29 30 remainder, whole_part = np.modf(arr) 31 remainder 32 whole_part 33 34 # 通用函数接收一个可选参数out,允许对数组按位操作 35 arr 36 np.sqrt(arr) 37 np.sqrt(arr, arr) 38 arr 39 40 41 # 使用数组进行面向数组编程 42 43 # 示例 想要对一些网格数据来计算函数sqrt(x^2+y^2)的值,np.meshgrid函数接收两个一维数组,并根据两个数组的所有(x,y)对生成一个二维矩阵 44 points = np.arange(-5, 5, 0.01) 45 xs, ys = np.meshgrid(points, points) 46 xs 47 ys 48 z = np.sqrt(xs ** 2 + ys ** 2) 49 z 50 51 # 使用matplotlib生成二维数组的可视化 52 import matplotlib.pyplot as plt 53 plt.imshow(z, cmap = plt.cm.gray);plt.colorbar() 54 plt.title("Image plot of $sqrt{x^2 + y^2}$ for a grid of values") 55 56 #将条件逻辑作为数组操作 57 # numpy.where函数是三元表达式x if condition else y 的向量化版本 58 xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5]) 59 yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5]) 60 cond = np.array([True, False, True, True, False]) 61 result = np.where(cond, xarr, yarr) 62 result 63 64 # 典型用法,根据一个数组生成一个新的数组,如将其中的正值替换为2,负值替换为-2 65 arr = np.random.randn(4, 4) 66 arr 67 arr > 0 68 np.where(arr > 0, 2, -2) 69 np.where(arr > 0, 2, arr)# 仅将正值设为2 70 71 # 数学和统计方法 72 arr = np.random.randn(5, 4) 73 arr 74 arr.mean() 75 np.mean(arr) 76 arr.sum() 77 # mean,sum等函数可以接受一个可选参数axis, 78 #用于计算给定轴向上的统计值,形成一个下降一维度的数组 79 #arr.mean(1)计算每一列的平均值,arr.sum(0)计算行轴向的累和 80 arr.mean(axis=1) 81 arr.sum(axis=0) 82 # 其他方法,cumsum,cumprod不会聚合,会产生一个中间结果 83 arr = np.array([0, 1, 2, 3, 4, 5, 6, 7]) 84 arr.cumsum() 85 # 在多维数组中,cumsum累积函数返回相同长度的数组,可以在指定轴向上根据较低维度的切片进行部分聚合 86 arr = np.array([[0, 1, 2], [3, 4, 5],[6, 7, 8]]) 87 arr 88 arr.cumsum(axis=0) 89 arr.cumprod(axis=1) 90 91 # 布尔值数组的方法 92 arr = np.random.randn(100) 93 (arr > 0).sum() 94 95 # 两个方法,any,all.any检查数组中是否至少有一个True,all检查是否每个值都是True 96 bools = np.array([False, False, True, False]) 97 bools.any() 98 bools.all() 99 100 # 排序 101 arr = np.random.randn(6) 102 arr 103 arr.sort() 104 arr 105 106 arr = np.random.randn(5, 3) 107 arr 108 109 arr.sort(1) 110 arr 111 112 # 针对一维ndarray的基础集合操作,常用一个方法 np.unique,返回的是数组中唯一值排序后形成的数组 113 names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe']) 114 np.unique(names) 115 116 ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4]) 117 np.unique(ints) 118 119 # np.in1d 可以检查一个数组中的值是否在另外一个数组中,并返回一个布尔数组 120 values = np.array([6, 0, 0, 3, 2, 5, 6]) 121 np.in1d(values, [2, 3, 6])
参考书籍:利用 python 进行数据分析
作者:舟华520
出处:https://www.cnblogs.com/xfzh193/
本文以学习,分享,研究交流为主,欢迎转载,请标明作者出处!