NumPy是一个开源免费的基于Python的科学计算包,这个系列的几篇文章就作为自己学习NumPy的学习笔记对自己的学习过程做一记录。所以,这系列的博客不求准确和全面,只是就我目前最新的理解谈一谈NumPy的具体使用,顺便也会涉及一些关于SciPy和Matplotlib的使用。
NumPy的官方网址是: http://numpy.scipy.org/,官方的说明是这样的:
The fundamental package needed for scientific computing with Python is called NumPy. This package contains:
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- tools for integrating C/C++ and Fortran code
- useful linear algebra, Fourier transform, and random number capabilities.
那么也就是说,NumPy是Python用于科学计算的基础包。可以实现类似于矩阵操作,随机数生成,以及线性回归等在内的较为简单的科学计算。那我们首先从几个简单例子看看它的使用方法:
1)高精度浮点数定义:
- 0.000000009
- 123.2E-10
2)矩阵定义
- 产生数据矩阵1: data = arange(50).reshape(5,10)
- 产生数据矩阵2: data = rand(5,5)
- 产生数据矩阵3: data = binomial(10,0.4,(5,5))
- 产生数据矩阵4: a.fill(3), a[:] = 3
3)矩阵的乘法,点乘和除法和点除
- 乘法: dot(a,b) # a,b 可以为两个大小一致的矩阵或者张量,下同
- 点乘: a * b
- 除法: (目前好像没有找到)
- 点除: a/b
- 对于向量: a*b 表示点乘,dot(a,b)表示内积
4)杂例
- r_: r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
- array([1, 2, 3, 0, 0, 4, 5, 6])
- array([1, 2, 3, 0, 0, 4, 5, 6])
- ndindex: for index in ndindex(2,2,3): print index
- (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2)
- linaalg: linalg.inv(a), linalg.norm(a)
数据种类 (http://docs.scipy.org/doc/numpy/user/basics.types.html)
Data type | Description |
---|---|
bool | Boolean (True or False) stored as a byte |
int | Platform integer (normally either int32 or int64) |
int8 | Byte (-128 to 127) |
int16 | Integer (-32768 to 32767) |
int32 | Integer (-2147483648 to 2147483647) |
int64 | Integer (9223372036854775808 to 9223372036854775807) |
uint8 | Unsigned integer (0 to 255) |
uint16 | Unsigned integer (0 to 65535) |
uint32 | Unsigned integer (0 to 4294967295) |
uint64 | Unsigned integer (0 to 18446744073709551615) |
float | Shorthand for float64. |
float32 | Single precision float: sign bit, 8 bits exponent, 23 bits mantissa |
float64 | Double precision float: sign bit, 11 bits exponent, 52 bits mantissa |
complex | Shorthand for complex128. |
complex64 | Complex number, represented by two 32-bit floats (real and imaginary components) |
complex128 | Complex number, represented by two 64-bit floats (real and imaginary components) |
NumPy包介绍:
SciPy 包介绍:
- __core_config__
- __scipy_config__
- __svn_version__
- _import_tools
- core_version
- fft, fft2, fftn — discrete Fourier transform. Also see fftshift, fftfreq.
- fftpack (package)
- integrate (package)
- interpolate (package)
- io (package)
- lib (package)
- linalg (package)
- old__init__
- optimize (package)
- scipy_version
- sparse (package)
- special (package)
- stats (package)
- test (package)
- utils (package)
大家应该对NumPy有了一个初步的印象了,简单来说,我们可以把NumPy看作是Python版的Matlab。 下一节我们将从Array开始,详细记录NumPy的向量操作。