Python 是一种高级的,动态的,多泛型的编程语言。Python代码很多时候看起来就像是伪代码一样,因此你可以使用很少的几行可读性很高的代码来实现一个非常强大的想法。
Numpy的主要数据类型是ndarray,即多维数组。它有以下几个属性:
ndarray.ndim:数组的维数
ndarray.shape:数组每一维的大小
ndarray.size:数组中全部元素的数量
ndarray.dtype:数组中元素的类型(numpy.int32, numpy.int16, and numpy.float64等)
ndarray.itemsize:每个元素占几个字节
例子:
>>> import numpy as np>>> a = np.arange(15).reshape(3, 5)>>> aarray([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])>>> a.shape(3, 5)>>> a.ndim2>>> a.dtype.name'int64'>>> a.itemsize8>>> a.size15>>> type(a)<type 'numpy.ndarray'>>>> b = np.array([6, 7, 8])>>> barray([6, 7, 8])>>> type(b)<type 'numpy.ndarray'>
使用array函数讲tuple和list转为array:
>>> import numpy as np>>> a = np.array([2,3,4])>>> aarray([2, 3, 4])>>> a.dtypedtype('int64')>>> b = np.array([1.2, 3.5, 5.1])>>> b.dtypedtype('float64')
多维数组:
>>> b = np.array([(1.5,2,3), (4,5,6)])>>> barray([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]])
生成数组的同时指定类型:
>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )>>> carray([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])
生成数组并赋为特殊值:
ones:全1
zeros:全0
empty:随机数,取决于内存情况
>>> np.zeros( (3,4) )array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])>>> np.ones( (2,3,4), dtype=np.int16 ) # dtype can also be specifiedarray([[[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]], [[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]]], dtype=int16)>>> np.empty( (2,3) ) # uninitialized, output may varyarray([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]])
生成均匀分布的array:
arange(最小值,最大值,步长)(左闭右开)
linspace(最小值,最大值,元素数量)
>>> np.arange( 10, 30, 5 )array([10, 15, 20, 25])>>> np.arange( 0, 2, 0.3 ) # it accepts float argumentsarray([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])>>> np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])>>> x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
新闻热点
疑难解答