NumPy Basic Notes

Source: Internet
Author: User
Tags mathematical functions

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  
  1. data1=[6,7.5,8,0,1] #创建列表
  2. Arr1=np.array (data1) #转换为数组
  3. Arr1.dtype #数据类型保存在dtype对象中
  4. data2=[[1,2,3,4],[5,6,7,8]] #创建嵌套序列 (a list made up of equal-length lists)
  5. Arr2=np.array (data2) #转换为多维数组
  6. Np.zeros (10) the full 0 array of #创建指定长度
  7. Np.ones ((3,6)) a full 1 array #创建指定长度的 (3 rows, 6 columns, two dimensions)
  8. Range (0) #创建指定数量的顺序列表 (built-in function, start by default)
  9. Arange ( #创建指定数量的顺序数组)
  10. Eye (#创建一个正方的N) xn Unit matrix
  11. Arr1=np.array ([1,2,3],dtype=np.float64) #解释为特定数据类型

operations between arrays and scalars

[Python]View PlainCopy 
    1. Arr=np.array ([[1.,2.,3.],[4.,5.,6.]]) #创建二维数组
    2. Arr*arr #行列号相同的数组元素间运算
    3. Arr-arr
    4. 1/arr
    5. arr*0.5

basic indexes and slices

[Python]View PlainCopy  
  1. Arr=np.arange (Ten)
  2. arr[5] #索引第6个元素
  3. arr[5:8] #索引第6到第9个元素作为数组
  4. arr[5:8]= #令第6到第9个元素等于12
  5. arr_slice=arr[5:8] #数组切片是原始数据的视图, any changes on the view will be reflected in the original array
  6. arr_slice[:]= #将数组切片的全部元素改为64
  7. arr[5:8].copy () #得到数组切片的一份副本
  8. Arr2d=np.array ([[1,2,3],[4,5,6],[7,8,9]])
  9. arr2d[2] #索引二维数组第3行
  10. arr2d[0][2] arr2d[0,2] #等价索引1行3列元素
  11. arr2d[:2] #索引第1行和第2行 (not including line 3rd)
  12. arr2d[:,:1] #索引第1列
  13. 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 
    1. Arr=np.arange (). Reshape ((3,5)) #生成顺序数组, 3 rows and 5 columns after shaping
    2. Arr. T #转置
    3. Arr=np.random.randn (6,3) #randn函数生成一些正态分布的随机数组 (6 rows, 3 columns)
    4. 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 
    1. Arr=np.arange (Ten)
    2. NP.SQRT (arr) #计算各元素的平方根 (arr**0.5)
    3. Exp #计算各元素指数ex;  ABS #绝对值;
    4. 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  
    1. xarr=np.array ([1.1,1.2,< Span class= "number" >1.3,1.4,1.5])      #两个数值数组   
    2. Yarr=np.array ([2.1,2.2,2.3, 2.4,2.5])   
    3. cond=np.array ([true,false, True,true,false])     # A Boolean array   
    4. 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 
    1. Arr=np.random.randn (5,4)
    2. Arr.mean ();  Np.mean (arr); Arr.sum ();
    3. 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 
    1. ARR=RANDN (+)
    2. (arr>0). SUM () #正值的数量
    3. Bools.any () #用于测试数组中是否存在一个或多个True
    4. 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  
    1. ARR=RANDN (8)
    2. Arr.sort ()
    3. Arr=randn (5,3)
    4. Arr.sort (0) #二维数组按列排序;  Arr.sort (1) #二维数组按行排序;

Uniqueness of

[Python]View PlainCopy  
    1. Ints=np.array ([3,3,3,2,2,1,1,4,4])
    2. Np.unique (names) #找出数组中的唯一值并返回已排序的结果

file input and output for arrays
NumPy can read or write text data or binary data on disk.

[Python]View PlainCopy  
  1. Arr=np.arange (Ten)
  2. Np.save (' Some_array ', arr) in #数组以未压缩的原始二进制格式保存在. npy file
  3. Np.load (' Some_array ') #通过np. Load reads an array on the disk
  4. Np.savez (' Array_archive.npz ', A=arr,b=arr) #将多个数组以保存在一个压缩文件中
  5. A=np.arange (0,0.5). Reshape (4,-1)
  6. Np.savetxt (' E:\\knakan\\a.txt ', a) save data #缺省按照 '%.18e ' format, separated by spaces
  7. Np.loadtxt (' E:\\kankan\\a.txt ')
  8. Np.savetxt (' E:\\kankan\\a.txt ', a,fmt= "%d", delimiter= ",") #改为保存为整数, separated by commas
  9. Np.loadtxt (' E:\\kankan\\a.txt ', delimiter= ",") #读入时也需指定逗号分隔

linear algebra

[Python]View PlainCopy 
    1. X=np.array ([[1.,2.,3.],[4.,5.,6.]])
    2. Y=np.array ([[6.,23.],[-1,7],[8,9]])
    3. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.