Numpy
一、属性:
 * ndarray.shape 返回一个元组,里面是各个维度的size 
 * ndarray.ndim 返回数组的维度 
 * ndarray.dtype 返回数组数据的类型 
二、方法:
 * np.array(x, dtype=complex) 接收一个数组, dtype指定数据类型, 
 * np.zeros( (3,4) ) 接收一个代表数组维度size的元组 
 * np.ones((3,4)) 同上 
 * np.arange(10, 30, 5) 返回一个起始为10,每次增加5,一直到30但不包括30的数组(本例返回[10, 15, 20, 
25]),一般会跟reshape配合使用。 
 * np.linspace( 0, 2, 9 ) 将0-2分为九份 
 * numpy.random.rand(d0, d1, ..., dn) Create an array of the given shape and 
populate it with random samples from a uniform distribution(均匀分布) over [0, 1). 
 * numpy.random.randn(d0, d1, ..., dn) 
功能与上面的类似,只不过randn是从标准正态分布中取值,如果不传入参数,则返回一个随机的数(取自标准正态分布)。要从 
$$ N(\mu, \sigma^2) $$
中取值可以用这个公式sigma * np.random.randn(...) + mu
 * a.ravel() # returns the array, flattened 
 * a.T # returns the array, transposed 
 * a.reshape(3,-1) If a dimension is given as -1 in a reshaping operation, the 
other dimensions are automatically calculated 
 * np.vstack((a,b))、np.hstack((a,b)) 
 * numpy.concatenate((a1, a2, ...), axis=0, out=None) Join a sequence of 
arrays along an existing axis. 按照指定的axis进行连接 
13.np.hsplit(a,(3,4)) # Split a after the third and the fourth 
column;类似的还有np.vsplit,这个是按行拆分,上面是按列拆分;
14.
运算:
 * a+b a-b a*b 都是elementwise 运算; 
 * a.dot(b) 矩阵相乘运算; 
 * np.sin(a) 对矩阵a中的元素进行三角函数运算(类似的np.exp(a)、 np.sqrt(a)); 
 * a**2 幂运算 
 * a<2 不等式运算。返回布尔值组成的数组,shape与a相同; 
 * a.sum() a.min() a.max(),三者都可接收一个axis作为参数,返回特定axis的sum、min、max 
Indexing, Slicing and Iterating
 * a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, 
exclusive, set every 2nd element to -1000(从开始到位置6,但不包括a[6],然后往前每隔一个设为-1000) 
 * a[ : :-1] # reversed a,将a进行反转。a是一维数组。 
 * 对于多维数组
for row in b: row是每一行。
for element in b.flat: element是每个元素。 
Copies and Views
有三种情况:
 * No Copy at All,比如b=a,b只是a的引用,不会有新的object被创建,b is a 会返回True 
 * View or Shallow Copy,比如c = a.view(),c is a返回False,但是c.base is 
a会返回True,c的值改变,会引起a的值改变,但是c的shape改变,不会引起a的shape改变; 
 * Deep Copy,比如 d = a.copy(),d is a 与d.base is a 
都会返回False,d是一个全新的对象,与a没有任何关系,d的改变不会引起a的改变。 
热门工具 换一换