您的位置:首页 > 编程语言 > Python开发

numpy module 1 -- Numpy tutorial

2016-07-12 12:18 429 查看


0. Numpy

Numpy is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment
of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation.

At the core of the NumPy package, is the ndarray object.
It keep homogeneous(同质的) data types.There are several
important differences between NumPy arrays and the standard Python sequences:

NumPy数组的尺寸是可变的。
元素类型要相同,内存位置可由加法计算。
数学计算更有效和便利。
很多科学计算包是基于Numpy的。
循环部分大多由C来写,计算速度更快。(near-C-speed)

Vectorization(向量化) and Broadcasting(广播):

(1)向量化:更简明易读、更短的代码意味着更少的错误、更接近标准数学符号、more "Pythonic"

(2)广播:统一相同尺寸。


1. The Basic

NumPy’s main object is the homogeneous(同质的) multidimensional(多维) array. It is a table of elements (usually numbers), all of the same type, indexed(索引) by
a tuple of positive integers. In Numpy dimensions are called axes(轴).
The number of axes is rank(阶).

Numpy’s
array class is called ndarray.
It is also known by the alias array.
Note that numpy.array is
not the same as the Standard Python Library classarray.array,
which only handles one-dimensional arrays and offers less functionality.

The
more important attributes of an ndarray object
are:

(1) ndarray.ndim : the number of axes

(2) ndarray.shape : For example (n,m)

(3) ndarray.size : the total elements, equal to n *m...

(4) ndarray.dtype : the type of the ele. One can create or specify dtype's using standard Python types.

(5) ndarray.itemsize : the ele's bytes, For example float64 has itemsize 8(64/8)

(6) ndarray.data : the buffer containing the actual ele of the array.(一般不用此属性,我们用索引)




2. Create arrays

(1) you
can create an array from a regular Python list or tuple using the array function. 



(2) array transforms
sequences of sequences into two-dimensional arrays, 

 array transforms
sequences of sequences of sequences into three-dimensional arrays.



(3) The type of the array can also be explicitly
specified at creation.



(4) When the eles are originally unknown, but its size is known. Numpy create it with placeholder(占位符).

The function zeros creates
an array full of zeros.

The function ones creates
an array full of ones.

The function empty creates
an array whose initial content is random and depends on the state of the memory.

By default, the dtype of the created array is float64.



(5) To
create sequences of numbersn, Numpyt use arange(Just like range) and linspace.




3. Printing Arrays

NumPy displays it in a similar way to nested lists, but with the following layout:
the last axis is printed from left to right,
the second-to-last is printed from top to bottom,
the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
One-dimensional(一维的) arrays are then printed as rows.
Bidimensionals(二维的)
as matrices.

Tridimensionals(三维的)
as lists of matrices. 



If
an array is too large to be printed, NumPy automatically skips the central part.



To
disable this behaviour and force NumPy to print the entire array, using set_print options.




4. Basic Operations

(1) A new array is created and filled with the result.



(2)
Unlike in many matrix languages, * is elementwise(元素乘).

The
matrix product(矩阵乘) can be performed using the dot function
or method:



(3) Some
operations, such as += and *=,
act in place to modify an existing array rather than create a new one.



(4)
When operating with arrays of different types, using upcasting(向上转型).



(5) Many unary operations,are
implemented as methods of the ndarray class. 



(6) by
specifying(指明) the axis parameter
you can apply an operation along the specified axis of an array:




5. Universal(通用的) Functions

NumPy provides familiar mathematical functions such as sin, cos, and exp. It called "universal functions"(ufunc).

Within
NumPy, these functions operate ele:



See also
allanyapply_along_axisargmaxargminargsortaveragebincountceil,clipconjcorrcoefcovcrosscumprodcumsumdiffdotfloorinner, inv,lexsortmaxmaximummeanmedianminminimumnonzeroouterprod,reroundsortstdsumtracetransposevarvdotvectorizewhere



6. Indexing(索引), Slicing(切片) and Iterating(迭代)

(1) One-dimensional arrays can be indexed,
sliced and iterated over, much like listsand
other Python sequences.



(2) Multidimensional arrays
can have one index per axis. These indices are given in a tuple:



(3)When fewer indices are provided than the number
of axes, the missing indices is :



x[1,2,...] is
equivalent to x[1,2,:,:,:],

x[...,3] to x[:,:,:,:,3] and

x[4,...,5,:] to x[4,:,:,5,:].



(4) 迭代默认发生在第0轴。ne can use the flat attribute
which is an iterator over
all the ele.




7. Shape Manipulation

(1) changing the shape of an array

C-stype arrays, the
rightmost index “changes the fastest”, so the element after a[0,0] is a[0,1].

FORTRAN-style
arrays, in which the leftmost index changes the fastest.



(2) The reshape function just modified shape, whereas the ndarray.resize modifies the array itself.

If a dimension is given as -1(自适应)



(3) stacking(堆积) together different arrays



(4) column_stack



(5) newaxis:增加一个轴



NOTES:For arrays of with more than two dimensions, hstack stacks
along their second axes(1轴), vstack stacks
along their first axes(0轴), and concatenate allows
for an optional arguments giving the number of the axis.

(6)splitting one array into several smaller ones

hsplit - split
an array along its horizontal axis,

vsplit
- splits along the vertical axis,

arrary_split
- allows one to specify along which axis to split.




8. Copies and Views

When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not.

(1) No copy

Simple assignments(操作) make no copy of array objects
or of their data.

Python passes mutable(易变的) objects as references(引用),
so function calls make no copy.



(2)view (shalow copy)
Different array objects can share the same
data. 



Slicing
an array returns a view of it.



(3) Deep Copy, using copy method




9. Functions and Methods Overview

Array Creation
arangearraycopyemptyempty_likeeyefromfilefromfunction,identitylinspacelogspacemgridogridonesones_like, r, zeros,zeros_like
Conversions
ndarray.astypeatleast_1datleast_2datleast_3dmat
Manipulations
array_splitcolumn_stackconcatenatediagonaldsplitdstackhsplit,hstackndarray.itemnewaxisravelrepeatreshaperesizesqueeze,swapaxestaketransposevsplitvstack
Questions
allanynonzerowhere
Ordering
argmaxargminargsortmaxminptpsearchsortedsort
Operations
choosecompresscumprodcumsuminnerndarray.fillimagprodput,putmaskrealsum
Basic Statistics
covmeanstdvar
Basic Linear Algebra
crossdotouterlinalg.svdvdot
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python numpy