python-numpy数组

网友投稿 232 2022-08-24


python-numpy数组

python-numpy数组

NumPy Basics: Arrays and¶# 优点:# NumPy是在⼀个连续的内存块中存储数据,独⽴于其他# Python内置对象。# NumPy可以在整个数组上执⾏复杂的计算,import numpy as npnp.random.seed(12345)import matplotlib.pyplot as pltplt.rc('figure', figsize=(10, 6))np.set_printoptions(precision=4, suppress=True)import numpy as npmy_arr = np.arange(1000000)my_list = list(range(1000000))# 查看语句性能%time for _ in range(10): my_arr2 = my_arr * 2%time for _ in range(10): my_list2 = [x * 2 for x in my_list]Wall time: 40.9 msWall time: 1.39 sThe NumPy ndarray: A Multidimensional Array Object使⽤标准的NumPy惯⽤# 法import numpy as np。你当然也可以在代码中使# ⽤from numpy import *,但不建议这么做。numpy的命名空# 间很⼤,包含许多函数# 4.1 NumPy的ndarray:⼀种多维数组对象# ⽣成⼀个包含随机数据的⼩数组:# 使⽤标准的NumPy惯⽤# 法import numpy as np。你当然也可以在代码中使# ⽤from numpy import *,但不建议这么做。numpy的命名空# 间很⼤,包含许多函数import numpy as np# Generate some random datadata = np.random.randn(2, 3)dataarray([[ 0.0929, 0.2817, 0.769 ], [ 1.2464, 1.0072, -1.2962]])# 进⾏数学运算data * 10data + dataarray([[ 0.1858, 0.5635, 1.538 ], [ 2.4929, 2.0144, -2.5924]])data.shapedata.dtypedtype('float64')Creating ndarrays# 创建NumPy数组data1 = [6, 7.5, 8, 0, 1]arr1 = np.array(data1)arr1array([6. , 7.5, 8. , 0. , 1. ])data2 = [[1, 2, 3, 4], [5, 6, 7, 8]]arr2 = np.array(data2)arr2array([[1, 2, 3, 4], [5, 6, 7, 8]])arr2.ndimarr2.shape(2, 4)arr1.dtypearr2.dtypedtype('int32')# zeros和onesnp.zeros(10)np.zeros((3, 6))np.empty((2, 3, 2))array([[[8.4766e-312, 3.1620e-322], [0.0000e+000, 0.0000e+000], [0.0000e+000, 4.2806e-037]], [[3.8853e-057, 2.2139e-052], [1.3929e+165, 4.2771e-033], [7.8692e-071, 1.2215e+165]]])np.arange(15)array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])Data Types for ndarrays设置数值类型# 创建数组,设置数值类型arr1 = np.array([1, 2, 3], dtype=np.float64)arr2 = np.array([1, 2, 3], dtype=np.int32)arr1.dtypearr2.dtypedtype('int32')# 转换类型 将⼀个数组从⼀个dtype转换成另⼀个dtypearr = np.array([1, 2, 3, 4, 5])arr.dtypefloat_arr = arr.astype(np.float64)float_arr.dtypedtype('float64')arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])arrarr.astype(np.int32)array([ 3, -1, -2, 0, 12, 10])numeric_strings = np.array(['1.25', '-9.6', '42'], dtype=np.string_)numeric_strings.astype(float)array([ 1.25, -9.6 , 42. ])int_array = np.arange(10)calibers = np.array([.22, .270, .357, .380, .44, .50], dtype=np.float64)int_array.astype(calibers.dtype)array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])empty_uint32 = np.empty(8, dtype='u4')empty_uint32array([ 0, 1075314688, 0, 1075707904, 0, 1075838976, 0, 1072693248], dtype=uint32)

数组计算 切片索引

Arithmetic with NumPy Arrays¶# NumPy数组的运算arr = np.array([[1., 2., 3.], [4., 5., 6.]])arrarr * arrarr - arrarray([[0., 0., 0.], [0., 0., 0.]])1 / arrarr ** 0.5arr2 = np.array([[0., 4., 1.], [7., 2., 12.]])arr2arr2 > arrBasic Indexing and Slicing# 基本的索引和切⽚arr = np.arange(10)arrarr[5]arr[5:8]arr[5:8] = 12arrarr_slice = arr[5:8]arr_slicearr_slice[1] = 12345arr# 切⽚[ : ]会给数组中的所有值赋值:arr_slice[:] = 64arrarr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])arr2d[2]array([7, 8, 9])arr2d[0][2]arr2d[0, 2]3arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])arr3darray([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]])arr3d[0]array([[1, 2, 3], [4, 5, 6]])# 复制数组old_values = arr3d[0].copy()arr3d[0] = 42arr3darr3d[0] = old_valuesarr3darray([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]])arr3d[1, 0]array([7, 8, 9])x = arr3d[1]xx[0]array([7, 8, 9])Indexing with slices# 切⽚索引arrarr[1:6]array([[4., 5., 6.]])arr2darr2d[:2]arr2d[:2, 1:]array([[2, 3], [5, 6]])arr2d[1, :2]array([4, 5])arr2d[:2, 2]array([3, 6])arr2d[:, :1]array([[1], [4], [7]])arr2d[:2, 1:] = 0arr2darray([[1, 0, 0], [4, 0, 0], [7, 8, 9]])

Boolean Indexing# 布尔型索引# numpy.random中的randn函数⽣成⼀些正态分布的随机数据:names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])data = np.random.randn(7, 4)namesdataarray([[ 0.275 , 0.2289, 1.3529, 0.8864], [-2.0016, -0.3718, 1.669 , -0.4386], [-0.5397, 0.477 , 3.2489, -1.0212], [-0.5771, 0.1241, 0.3026, 0.5238], [ 0.0009, 1.3438, -0.7135, -0.8312], [-2.3702, -1.8608, -0.8608, 0.5601], [-1.2659, 0.1198, -1.0635, 0.3329]])names == 'Bob'data[names == 'Bob']data[names == 'Bob', 2:]data[names == 'Bob', 3]names != 'Bob'data[~(names == 'Bob')]cond = names == 'Bob'data[~cond]mask = (names == 'Bob') | (names == 'Will')maskdata[mask]data[data < 0] = 0dataarray([[0.275 , 0.2289, 1.3529, 0.8864], [0. , 0. , 1.669 , 0. ], [0. , 0.477 , 3.2489, 0. ], [0. , 0.1241, 0.3026, 0.5238], [0.0009, 1.3438, 0. , 0. ], [0. , 0. , 0. , 0.5601], [0. , 0.1198, 0. , 0.3329]])data[names != 'Joe'] = 7dataarray([[7. , 7. , 7. , 7. ], [0. , 0. , 1.669 , 0. ], [7. , 7. , 7. , 7. ], [7. , 7. , 7. , 7. ], [7. , 7. , 7. , 7. ], [0. , 0. , 0. , 0.5601], [0. , 0.1198, 0. , 0.3329]])Fancy Indexing花式索引# 花式索引(Fancy indexing)是⼀个NumPy术语,它指的是利⽤# 整数数组进⾏索引。假设我们有⼀个8×4数组:# 花式索引# 花式索引(Fancy indexing)是⼀个NumPy术语,它指的是利⽤# 整数数组进⾏索引。假设我们有⼀个8×4数组:arr = np.empty((8, 4))for i in range(8): arr[i] = iarrarray([[0., 0., 0., 0.], [1., 1., 1., 1.], [2., 2., 2., 2.], [3., 3., 3., 3.], [4., 4., 4., 4.], [5., 5., 5., 5.], [6., 6., 6., 6.], [7., 7., 7., 7.]])arr[[4, 3, 0, 6]]array([[4., 4., 4., 4.], [3., 3., 3., 3.], [0., 0., 0., 0.], [6., 6., 6., 6.]])arr[[-3, -5, -7]]array([[5., 5., 5., 5.], [3., 3., 3., 3.], [1., 1., 1., 1.]])arr = np.arange(32).reshape((8, 4))arrarr[[1, 5, 7, 2], [0, 3, 1, 2]]arr[[1, 5, 7, 2]][:, [0, 3, 1, 2]]Transposing Arrays and Swapping Axesarr = np.arange(15).reshape((3, 5))arrarr.Tarr = np.random.randn(6, 3)arrnp.dot(arr.T, arr)arr = np.arange(16).reshape((2, 2, 4))arrarr.transpose((1, 0, 2))arrarr.swapaxes(1, 2)Universal Functions: Fast Element-Wise Array Functionsarr = np.arange(10)arrnp.sqrt(arr)np.exp(arr)x = np.random.randn(8)y = np.random.randn(8)xynp.maximum(x, y)arr = np.random.randn(7) * 5arrremainder, whole_part = np.modf(arr)remainderwhole_partarrnp.sqrt(arr)np.sqrt(arr, arr)arrarrnp.sqrt(arr)np.sqrt(arr, arr)

Array-Oriented Programming with Arrays# 4.3 利⽤数组进⾏数据处理points = np.arange(-5, 5, 0.01) # 1000 equally spaced pointsxs, ys = np.meshgrid(points, points)ysarray([[-5. , -5. , -5. , ..., -5. , -5. , -5. ], [-4.99, -4.99, -4.99, ..., -4.99, -4.99, -4.99], [-4.98, -4.98, -4.98, ..., -4.98, -4.98, -4.98], ..., [ 4.97, 4.97, 4.97, ..., 4.97, 4.97, 4.97], [ 4.98, 4.98, 4.98, ..., 4.98, 4.98, 4.98], [ 4.99, 4.99, 4.99, ..., 4.99, 4.99, 4.99]])z = np.sqrt(xs ** 2 + ys ** 2)zarray([[7.0711, 7.064 , 7.0569, ..., 7.0499, 7.0569, 7.064 ], [7.064 , 7.0569, 7.0499, ..., 7.0428, 7.0499, 7.0569], [7.0569, 7.0499, 7.0428, ..., 7.0357, 7.0428, 7.0499], ..., [7.0499, 7.0428, 7.0357, ..., 7.0286, 7.0357, 7.0428], [7.0569, 7.0499, 7.0428, ..., 7.0357, 7.0428, 7.0499], [7.064 , 7.0569, 7.0499, ..., 7.0428, 7.0499, 7.0569]]) 网格# 画图 网格import matplotlib.pyplot as pltplt.imshow(z, cmap=plt.cm.gray); plt.colorbar()plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")Text(0.5,1,'Image plot of $\\sqrt{x^2 + y^2}$ for a grid of values')plt.draw()

plt.close('all')Expressing Conditional Logic as Array Operations# 将条件逻辑表述为数组运算xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])cond = np.array([True, False, True, True, False])result = [(x if c else y) for x, y, c in zip(xarr, yarr, cond)]resultresult = np.where(cond, xarr, yarr)resultarr = np.random.randn(4, 4)arrarr > 0np.where(arr > 0, 2, -2)np.where(arr > 0, 2, arr) # set only positive values to 2Mathematical and Statistical Methods可以通过数组上的⼀组数学函数对整个数组或某个轴向的数据进# ⾏统计计算。sum、mean以及标准差std等聚合计算# (aggregation,通常叫做约简(reduction))既可以当做数组# 的实例⽅法调⽤,也可以当做顶级NumPy函数使⽤。# 数学和统计⽅法# 可以通过数组上的⼀组数学函数对整个数组或某个轴向的数据进# ⾏统计计算。sum、mean以及标准差std等聚合计算# (aggregation,通常叫做约简(reduction))既可以当做数组# 的实例⽅法调⽤,也可以当做顶级NumPy函数使⽤。arr = np.random.randn(5, 4)arrarr.mean()np.mean(arr)arr.sum()-3.1212770951357607arr.mean(axis=1)arr.sum(axis=0)array([ 1.1644, -2.4154, -1.0308, -0.8396])arr = np.array([0, 1, 2, 3, 4, 5, 6, 7])arr.cumsum()array([ 0, 1, 3, 6, 10, 15, 21, 28], dtype=int32)# 累加函数(如cumsum)arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])arrarr.cumsum(axis=0)arr.cumprod(axis=1)array([[ 0, 0, 0], [ 3, 12, 60], [ 6, 42, 336]], dtype=int32)Methods for Boolean Arraysarr = np.random.randn(100)(arr > 0).sum() # Number of positive valuesbools = np.array([False, False, True, False])bools.any()bools.all()Sorting# 排序# 跟Python内置的列表类型⼀样,NumPy数组也可以通过sort⽅法# 就地排序:arr = np.random.randn(6)arrarr.sort()arrarray([-1.1577, 0.0513, 0.4336, 0.8167, 1.0107, 1.8249])arr = np.random.randn(5, 3)arrarr.sort(1)arrlarge_arr = np.random.randn(1000)large_arr.sort()large_arr[int(0.05 * len(large_arr))] # 5% quantileUnique and Other Set Logic唯⼀化以及其它的集合逻辑# NumPy提供了⼀些针对⼀维ndarray的基本集合运算。最常⽤的# 可能要数np.unique了,# 唯⼀化以及其它的集合逻辑# NumPy提供了⼀些针对⼀维ndarray的基本集合运算。最常⽤的# 可能要数np.unique了,names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])np.unique(names)ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4])np.unique(ints)array([1, 2, 3, 4])sorted(set(names))values = np.array([6, 0, 0, 3, 2, 5, 6])np.in1d(values, [2, 3, 6])array([ True, False, False, True, True, False, True])

File Input and Output with Arrays# 4.4 ⽤于数组的⽂件输⼊输出# np.save和np.load是读写磁盘数组数据的两个主要函数。arr = np.arange(10)np.save('some_array', arr)np.load('some_array.npy')np.savez('array_archive.npz', a=arr, b=arr)arch = np.load('array_archive.npz')arch['b']np.savez_compressed('arrays_compressed.npz', a=arr, b=arr)!rm some_array.npy!rm array_archive.npz!rm arrays_compressed.npzLinear Algebra线性代数(如矩阵乘法、矩阵分解、⾏列式以及其他⽅阵数学# 等)是任何数组库的重要组成部分。不像某些语⾔(如# MATLAB),通过*对两个⼆维数组相乘得到的是⼀个元素级的# 积,⽽不是⼀个矩阵点积。因此,NumPy提供了⼀个⽤于矩阵# 乘法的dot函数(既是⼀个数组⽅法也是numpy命名空间中的⼀# 个函数):# 线性代数(如矩阵乘法、矩阵分解、⾏列式以及其他⽅阵数学# 等)是任何数组库的重要组成部分。不像某些语⾔(如# MATLAB),通过*对两个⼆维数组相乘得到的是⼀个元素级的# 积,⽽不是⼀个矩阵点积。因此,NumPy提供了⼀个⽤于矩阵# 乘法的dot函数(既是⼀个数组⽅法也是numpy命名空间中的⼀# 个函数):x = np.array([[1., 2., 3.], [4., 5., 6.]])y = np.array([[6., 23.], [-1, 7], [8, 9]])xyx.dot(y)np.dot(x, y)np.dot(x, np.ones(3))x @ np.ones(3)from numpy.linalg import inv, qrX = np.random.randn(5, 5)mat = X.T.dot(X)inv(mat)mat.dot(inv(mat))q, r = qr(mat)rPseudorandom Number Generationnumpy.random模块对Python内置的random进⾏了补充,增加了# ⼀些⽤于⾼效⽣成多种概率分布的样本值的函数。例如,你可以# ⽤normal来得到⼀个标准正态分布的4×4样本数组:# 4.6 伪随机数⽣成# numpy.random模块对Python内置的random进⾏了补充,增加了# ⼀些⽤于⾼效⽣成多种概率分布的样本值的函数。例如,你可以# ⽤normal来得到⼀个标准正态分布的4×4样本数组:samples = np.random.normal(size=(4, 4))samplesarray([[-0.9975, 0.8506, -0.1316, 0.9124], [ 0.1882, 2.1695, -0.1149, 2.0037], [ 0.0296, 0.7953, 0.1181, -0.7485], [ 0.585 , 0.1527, -1.5657, -0.5625]])from random import normalvariateN = 1000000%timeit samples = [normalvariate(0, 1) for _ in range(N)]%timeit np.random.normal(size=N)np.random.seed(1234)rng = np.random.RandomState(1234)rng.randn(10)Example: Random Walks# 4.7 示例:随机漫步import randomposition = 0walk = [position]steps = 1000for i in range(steps): step = 1 if random.randint(0, 1) else -1 position += step walk.append(position)plt.figure()

# 折线图plt.plot(walk[:100])[]np.random.seed(12345)nsteps = 1000draws = np.random.randint(0, 2, size=nsteps)steps = np.where(draws > 0, 1, -1)walk = steps.cumsum()walk.min()walk.max()(np.abs(walk) >= 10).argmax()Simulating Many Random Walks at Oncenwalks = 5000nsteps = 1000draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1steps = np.where(draws > 0, 1, -1)walks = steps.cumsum(1)walkswalks.max()walks.min()hits30 = (np.abs(walks) >= 30).any(1)hits30hits30.sum() # Number that hit 30 or -30crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)crossing_times.mean()steps = np.random.normal(loc=0, scale=0.25, size=(nwalks, nsteps))Conclusion##############################自己的其他补充:# 在-10和10之间生成一个数列,共100个数x = np.linspace(-10, 10, 100)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python_字典(python字典的增删改查)
下一篇:python_datafram两列拼接,中间加上特殊字符(python列拼接dataframe)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~