本文将帮助您了解Python中广泛使用的数组处理库, 努比 .
什么是NumPy? NumPy是一个通用阵列处理包。它提供了一个高性能的多维数组对象,以及用于处理这些数组的工具。
它是使用Python进行科学计算的基本软件包。它包含各种功能,包括以下重要功能:
- 一个强大的N维数组对象
- 复杂的(广播)功能
- 集成C/C++和Fortran代码的工具
- 有用的线性代数、傅立叶变换和随机数功能
除了其明显的科学用途外,NumPy还可以用作通用数据的高效多维容器。 可以使用Numpy定义任意数据类型,这使Numpy能够无缝、快速地与各种数据库集成。
安装:
- 雨衣 和 Linux 用户可以通过pip命令安装NumPy:
pip install numpy
- 窗户 没有任何类似于linux或mac的包管理器。 请从下载预装windows installer for NumPy 在这里 (根据您的系统配置和Python版本)。 然后手动安装软件包。
注: 下面讨论的所有示例都不会在计算机上运行 在线IDE。
1.NumPy中的阵列: NumPy的主要对象是同构多维数组。
- 它是一个由相同类型的元素(通常是数字)组成的表,由一个正整数元组索引。
- 在NumPy中,维度被称为 斧头 .轴的数量为 等级 .
- NumPy的数组类被称为 恩达雷 .它也被称为别名 大堆 .
例子:
[[ 1, 2, 3], [ 4, 2, 5]] Here, rank = 2 (as it is 2-dimensional or it has 2 axes) first dimension(axis) length = 2, second dimension has length = 3 overall shape can be expressed as: (2, 3)
Python3
# Python program to demonstrate # basic array characteristics import numpy as np # Creating array object arr = np.array( [[ 1 , 2 , 3 ], [ 4 , 2 , 5 ]] ) # Printing type of arr object print ( "Array is of type: " , type (arr)) # Printing array dimensions (axes) print ( "No. of dimensions: " , arr.ndim) # Printing shape of array print ( "Shape of array: " , arr.shape) # Printing size (total number of elements) of array print ( "Size of array: " , arr.size) # Printing type of elements in array print ( "Array stores elements of type: " , arr.dtype) |
Array is of type: No. of dimensions: 2 Shape of array: (2, 3) Size of array: 6 Array stores elements of type: int64
2.数组创建: 在NumPy中创建数组有多种方法。
- 例如,可以从常规Python创建数组 列表 或 元组 使用 大堆 作用结果阵列的类型是根据序列中元素的类型推导出来的。
- 通常,数组的元素最初是未知的,但其大小是已知的。因此,NumPy提供了几个函数来创建数组 初始占位符内容 。这样可以最大限度地减少增加阵列的必要性,这是一项昂贵的操作。 例如: NP零,np。一个,np。全,np。空的等等。
- 为了创建数字序列,NumPy提供了一个类似于range的函数,它返回数组而不是列表。
- 阿兰奇: 返回给定间隔内的等间距值。 步 指定大小。
- linspace: 返回给定间隔内的等间距值。 号码 返回的元素数。
- 重塑阵列: 我们可以使用 重塑 方法来重塑数组。考虑具有形状的数组(A1,A2,A3,…,AN)。我们可以将其重塑并转换为另一个具有形状(b1、b2、b3、…、bM)的阵列。唯一需要的条件是: a1 x a2 x a3…x aN=b1 x b2 x b3…x bM。(即阵列的原始大小保持不变。)
- 展平阵列: 我们可以使用 压平 方法获取折叠到中的数组副本 一维 .它接受 顺序 论点默认值为“C”(用于行主顺序)。使用“F”表示列的主要顺序。
注: 可以在创建数组时显式定义数组类型。
Python3
# Python program to demonstrate # array creation techniques import numpy as np # Creating array from list with type float a = np.array([[ 1 , 2 , 4 ], [ 5 , 8 , 7 ]], dtype = 'float' ) print ( "Array created using passed list:" , a) # Creating array from tuple b = np.array(( 1 , 3 , 2 )) print ( "Array created using passed tuple:" , b) # Creating a 3X4 array with all zeros c = np.zeros(( 3 , 4 )) print ( "An array initialized with all zeros:" , c) # Create a constant value array of complex type d = np.full(( 3 , 3 ), 6 , dtype = 'complex' ) print ( "An array initialized with all 6s." "Array type is complex:" , d) # Create an array with random values e = np.random.random(( 2 , 2 )) print ( "A random array:" , e) # Create a sequence of integers # from 0 to 30 with steps of 5 f = np.arange( 0 , 30 , 5 ) print ( "A sequential array with steps of 5:" , f) # Create a sequence of 10 values in range 0 to 5 g = np.linspace( 0 , 5 , 10 ) print ( "A sequential array with 10 values between" "0 and 5:" , g) # Reshaping 3X4 array to 2X2X3 array arr = np.array([[ 1 , 2 , 3 , 4 ], [ 5 , 2 , 4 , 2 ], [ 1 , 2 , 0 , 1 ]]) newarr = arr.reshape( 2 , 2 , 3 ) print ( "Original array:" , arr) print ( "Reshaped array:" , newarr) # Flatten array arr = np.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]) flarr = arr.flatten() print ( "Original array:" , arr) print ( "Fattened array:" , flarr) |
Array created using passed list: [[ 1. 2. 4.] [ 5. 8. 7.]] Array created using passed tuple: [1 3 2] An array initialized with all zeros: [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] An array initialized with all 6s. Array type is complex: [[ 6.+0.j 6.+0.j 6.+0.j] [ 6.+0.j 6.+0.j 6.+0.j] [ 6.+0.j 6.+0.j 6.+0.j]] A random array: [[ 0.46829566 0.67079389] [ 0.09079849 0.95410464]] A sequential array with steps of 5: [ 0 5 10 15 20 25] A sequential array with 10 values between 0 and 5: [ 0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ] Original array: [[1 2 3 4] [5 2 4 2] [1 2 0 1]] Reshaped array: [[[1 2 3] [4 5 2]] [[4 2 1] [2 0 1]]] Original array: [[1 2 3] [4 5 6]] Fattened array: [1 2 3 4 5 6]
3.数组索引: 了解数组索引的基础知识对于分析和操作数组对象很重要。NumPy提供了许多方法来进行数组索引。
- 切片: 就像python中的列表一样,NumPy数组可以被切片。由于数组可以是多维的,所以需要为数组的每个维度指定一个切片。
- 整数数组索引: 在这个方法中,为每个维度传递索引列表。对相应的元素进行一对一映射,构造一个新的任意数组。
- 布尔数组索引: 当我们想要从数组中选取满足某些条件的元素时,就使用这种方法。
Python3
# Python program to demonstrate # indexing in numpy import numpy as np # An exemplar array arr = np.array([[ - 1 , 2 , 0 , 4 ], [ 4 , - 0.5 , 6 , 0 ], [ 2.6 , 0 , 7 , 8 ], [ 3 , - 7 , 4 , 2.0 ]]) # Slicing array temp = arr[: 2 , :: 2 ] print ( "Array with first 2 rows and alternate" "columns(0 and 2):" , temp) # Integer array indexing example temp = arr[[ 0 , 1 , 2 , 3 ], [ 3 , 2 , 1 , 0 ]] print ( "Elements at indices (0, 3), (1, 2), (2, 1)," "(3, 0):" , temp) # boolean array indexing example cond = arr > 0 # cond is a boolean array temp = arr[cond] print ( "Elements greater than 0:" , temp) |
Array with first 2 rows and alternatecolumns(0 and 2): [[-1. 0.] [ 4. 6.]] Elements at indices (0, 3), (1, 2), (2, 1),(3, 0): [ 4. 6. 0. 3.] Elements greater than 0: [ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]
4.基本操作: NumPy中提供了过多的内置算术函数。
- 单个阵列上的操作: 我们可以使用重载算术运算符对数组进行元素操作,以创建新数组。如果使用+=、-=、*=运算符,则会修改现有数组。
Python3
# Python program to demonstrate # basic operations on single array import numpy as np a = np.array([ 1 , 2 , 5 , 3 ]) # add 1 to every element print ( "Adding 1 to every element:" , a + 1 ) # subtract 3 from each element print ( "Subtracting 3 from each element:" , a - 3 ) # multiply each element by 10 print ( "Multiplying each element by 10:" , a * 10 ) # square each element print ( "Squaring each element:" , a * * 2 ) # modify existing array a * = 2 print ( "Doubled each element of original array:" , a) # transpose of array a = np.array([[ 1 , 2 , 3 ], [ 3 , 4 , 5 ], [ 9 , 6 , 0 ]]) print ( "Original array:" , a) print ( "Transpose of array:" , a.T) |
Adding 1 to every element: [2 3 6 4] Subtracting 3 from each element: [-2 -1 2 0] Multiplying each element by 10: [10 20 50 30] Squaring each element: [ 1 4 25 9] Doubled each element of original array: [ 2 4 10 6] Original array: [[1 2 3] [3 4 5] [9 6 0]] Transpose of array: [[1 3 9] [2 4 6] [3 5 0]]
- 一元运算符: 许多一元运算是作为一种计算方法提供的 恩达雷 班这包括sum、min、max等。这些函数也可以通过设置轴参数按行或按列应用。
Python3
# Python program to demonstrate # unary operators in numpy import numpy as np arr = np.array([[ 1 , 5 , 6 ], [ 4 , 7 , 2 ], [ 3 , 1 , 9 ]]) # maximum element of array print ( "Largest element is:" , arr. max ()) print ( "Row-wise maximum elements:" , arr. max (axis = 1 )) # minimum element of array print ( "Column-wise minimum elements:" , arr. min (axis = 0 )) # sum of array elements print ( "Sum of all array elements:" , arr. sum ()) # cumulative sum along each row print ( "Cumulative sum along each row:" , arr.cumsum(axis = 1 )) |
输出:
Largest element is: 9 Row-wise maximum elements: [6 7 9] Column-wise minimum elements: [1 1 2] Sum of all array elements: 38 Cumulative sum along each row: [[ 1 6 12] [ 4 11 13] [ 3 4 13]]
- 二进制运算符: 这些操作应用于array elementwise,并创建一个新数组。可以使用所有基本的算术运算符,如+、-、/, 在+=,-=,的情况下, =运算符,修改现有数组。
Python3
# Python program to demonstrate # binary operators in Numpy import numpy as np a = np.array([[ 1 , 2 ], [ 3 , 4 ]]) b = np.array([[ 4 , 3 ], [ 2 , 1 ]]) # add arrays print ( "Array sum:" , a + b) # multiply arrays (elementwise multiplication) print ( "Array multiplication:" , a * b) # matrix multiplication print ( "Matrix multiplication:" , a.dot(b)) |
输出:
Array sum: [[5 5] [5 5]] Array multiplication: [[4 6] [6 4]] Matrix multiplication: [[ 8 5] [20 13]]
- 通用功能(ufunc): NumPy提供了熟悉的数学函数,如sin、cos、exp等。这些函数还对数组进行元素操作,生成一个数组作为输出。
注: 我们上面使用重载运算符所做的所有操作都可以使用像np这样的UFUNC来完成。加上,np。减法,np。乘法,np。除法,np。总数等。
Python3
# Python program to demonstrate # universal functions in numpy import numpy as np # create an array of sine values a = np.array([ 0 , np.pi / 2 , np.pi]) print ( "Sine values of array elements:" , np.sin(a)) # exponential values a = np.array([ 0 , 1 , 2 , 3 ]) print ( "Exponent of array elements:" , np.exp(a)) # square root of array values print ( "Square root of array elements:" , np.sqrt(a)) |
Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-16] Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692] Square root of array elements: [ 0. 1. 1.41421356 1.73205081]
4.排序数组: 有一个简单的例子 NP分类 排序NumPy数组的方法。让我们来探索一下。
Python3
# Python program to demonstrate sorting in numpy import numpy as np a = np.array([[ 1 , 4 , 2 ], [ 3 , 4 , 6 ], [ 0 , - 1 , 5 ]]) # sorted array print ( "Array elements in sorted order:" , np.sort(a, axis = None )) # sort array row-wise print ( "Row-wise sorted array:" , np.sort(a, axis = 1 )) # specify sort algorithm print ( "Column wise sort by applying merge-sort:" , np.sort(a, axis = 0 , kind = 'mergesort' )) # Example to show sorting of structured array # set alias names for dtypes dtypes = [( 'name' , 'S10' ), ( 'grad_year' , int ), ( 'cgpa' , float )] # Values to be put in array values = [( 'Hrithik' , 2009 , 8.5 ), ( 'Ajay' , 2008 , 8.7 ), ( 'Pankaj' , 2008 , 7.9 ), ( 'Aakash' , 2009 , 9.0 )] # Creating array arr = np.array(values, dtype = dtypes) print ( "Array sorted by names:" , np.sort(arr, order = 'name' )) print ( "Array sorted by grauation year and then cgpa:" , np.sort(arr, order = [ 'grad_year' , 'cgpa' ])) |
Array elements in sorted order: [-1 0 1 2 3 4 4 5 6] Row-wise sorted array: [[ 1 2 4] [ 3 4 6] [-1 0 5]] Column wise sort by applying merge-sort: [[ 0 -1 2] [ 1 4 5] [ 3 4 6]] Array sorted by names: [('Aakash', 2009, 9.0) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5) ('Pankaj', 2008, 7.9)] Array sorted by grauation year and then cgpa: [('Pankaj', 2008, 7.9) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5) ('Aakash', 2009, 9.0)]
所以,这是一个简短而简洁的介绍,也是NumPy图书馆的教程。 有关更详细的研究,请参阅 NumPy参考指南 . 本文由Nikhil Kumar撰稿。如果你喜欢GeekSforgeks并想贡献自己的力量,你也可以用write写一篇文章。极客。组织或邮寄你的文章进行评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。