NumPy Introduction
Numpy (short for numerical Python) is the foundation package for high-performance scientific computing and data analysis. Some of its functions are as follows:
①ndarray, a fast and space-saving multidimensional array with vector arithmetic operations and complex broadcast capabilities.
② is a standard mathematical function for fast operation of whole sets of data (no need to write loops).
③ Tools for reading and writing disk data, and tools for manipulating memory-mapped files.
④ linear algebra, random number generation, and Fourier transform functions.
⑤ Tools for integrating code written in C, C + +, Fortran, and other languages.
Create an array
The simplest way to create an array is to use the array function. It accepts all sequences of objects (including other arrays) and then produces a new NumPy array containing the incoming data. Take a list of conversions as an example:
[Python]View PlainCopy
- data1=[6,7.5,8,0,1] #创建列表
- Arr1=np.array (data1) #转换为数组
- Arr1.dtype #数据类型保存在dtype对象中
- data2=[[1,2,3,4],[5,6,7,8]] #创建嵌套序列 (a list made up of equal-length lists)
- Arr2=np.array (data2) #转换为多维数组
- Np.zeros (10) the full 0 array of #创建指定长度
- Np.ones ((3,6)) a full 1 array #创建指定长度的 (3 rows, 6 columns, two dimensions)
- Range (0) #创建指定数量的顺序列表 (built-in function, start by default)
- Arange ( #创建指定数量的顺序数组)
- Eye (#创建一个正方的N) xn Unit matrix
- Arr1=np.array ([1,2,3],dtype=np.float64) #解释为特定数据类型
operations between arrays and scalars
[Python]View PlainCopy
- Arr=np.array ([[1.,2.,3.],[4.,5.,6.]]) #创建二维数组
- Arr*arr #行列号相同的数组元素间运算
- Arr-arr
- 1/arr
- arr*0.5
basic indexes and slices
[Python]View PlainCopy
- Arr=np.arange (Ten)
- arr[5] #索引第6个元素
- arr[5:8] #索引第6到第9个元素作为数组
- arr[5:8]= #令第6到第9个元素等于12
- arr_slice=arr[5:8] #数组切片是原始数据的视图, any changes on the view will be reflected in the original array
- arr_slice[:]= #将数组切片的全部元素改为64
- arr[5:8].copy () #得到数组切片的一份副本
- Arr2d=np.array ([[1,2,3],[4,5,6],[7,8,9]])
- arr2d[2] #索引二维数组第3行
- arr2d[0][2] arr2d[0,2] #等价索引1行3列元素
- arr2d[:2] #索引第1行和第2行 (not including line 3rd)
- arr2d[:,:1] #索引第1列
- arr2d[:-2] #使用负数索引将从尾部开始选取行
array Transpose and axis swapping
Transpose (transpose) is a special form of remodeling that returns a view of the source data (no copy operation).
[Python]View PlainCopy
- Arr=np.arange (). Reshape ((3,5)) #生成顺序数组, 3 rows and 5 columns after shaping
- Arr. T #转置
- Arr=np.random.randn (6,3) #randn函数生成一些正态分布的随机数组 (6 rows, 3 columns)
- Np.dot (arr. T,arr) #利用np. Dot Compute matrix inner product XTX
general functions: fast element Progression Group functions
A general function (that is, ufunc) is a function that performs an element-level operation on data in Ndarray.
[Python]View PlainCopy
- Arr=np.arange (Ten)
- NP.SQRT (arr) #计算各元素的平方根 (arr**0.5)
- Exp #计算各元素指数ex; ABS #绝对值;
- Np.add (x, y) #x, y array of corresponding elements added; Subtract #相减; Multiply #相乘; Divide #相除;
using arrays for data processing
The practice of replacing loops with array expressions, often called vectorization
describe conditional logic as an array operation
The Numpy.where function is a vectorized version of the ternary expression x if condition else y
[Python]View PlainCopy
- xarr=np.array ([1.1,1.2,< Span class= "number" >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]) # A Boolean array
- result=np.where (Cond,xarr,yarr) #三元表达式
mathematical and statistical methods
You can use a set of mathematical functions on an array to calculate the data for an entire array or an axis. Aggregate calculations such as Sum, mean, and standard deviation STD (aggregation, commonly called reduction (reduction)) can be used as an instance method call to an array, or as a top-level numpy function:
[Python]View PlainCopy
- Arr=np.random.randn (5,4)
- Arr.mean (); Np.mean (arr); Arr.sum ();
- Arr.mean (axis=1) #计算该轴上的统计值 (0 for columns, 1 for rows)
Methods for arrays of Boolean types
Boolean values are cast to 1 (True) and 0 (False). Therefore, sum is often used to count the true value in a Boolean array:
[Python]View PlainCopy
- ARR=RANDN (+)
- (arr>0). SUM () #正值的数量
- Bools.any () #用于测试数组中是否存在一个或多个True
- Bools.all () #用于测试数组中所有值是否都是True
Sort
Like Python's built-in list type, numpy arrays can be sorted in place by the Sort method (modifying the array itself).
[Python]View PlainCopy
- ARR=RANDN (8)
- Arr.sort ()
- Arr=randn (5,3)
- Arr.sort (0) #二维数组按列排序; Arr.sort (1) #二维数组按行排序;
Uniqueness of
[Python]View PlainCopy
- Ints=np.array ([3,3,3,2,2,1,1,4,4])
- Np.unique (names) #找出数组中的唯一值并返回已排序的结果
file input and output for arrays
NumPy can read or write text data or binary data on disk.
[Python]View PlainCopy
- Arr=np.arange (Ten)
- Np.save (' Some_array ', arr) in #数组以未压缩的原始二进制格式保存在. npy file
- Np.load (' Some_array ') #通过np. Load reads an array on the disk
- Np.savez (' Array_archive.npz ', A=arr,b=arr) #将多个数组以保存在一个压缩文件中
- A=np.arange (0,0.5). Reshape (4,-1)
- Np.savetxt (' E:\\knakan\\a.txt ', a) save data #缺省按照 '%.18e ' format, separated by spaces
- Np.loadtxt (' E:\\kankan\\a.txt ')
- Np.savetxt (' E:\\kankan\\a.txt ', a,fmt= "%d", delimiter= ",") #改为保存为整数, separated by commas
- Np.loadtxt (' E:\\kankan\\a.txt ', delimiter= ",") #读入时也需指定逗号分隔
linear algebra
[Python]View PlainCopy
- X=np.array ([[1.,2.,3.],[4.,5.,6.]])
- Y=np.array ([[6.,23.],[-1,7],[8,9]])
- X.dot (y) #矩阵乘法, equivalent to Np.dot (x, y)
"References"
[1]. Using Python for data analysis, Wes McKinney, Tang Xue, 2014, Mechanical industry Press
NumPy Basic Notes