numpy基本操作

NumPy系统是Python的一种开源的数组计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix))。

数组是Numpy操作的主要对象,也是python数据分析的主要对象。

NumPy数组是一个多维数组对象,称为ndarray。其由两部分组成:

  • 实际的数据
  • 描述这些数据的元数据

大部分操作仅针对于元数据,而不改变底层实际的数据。

关于NumPy数组有几点必需了解的:

  • NumPy数组的下标从0开始。
  • 同一个NumPy数组中所有元素的类型必须是相同的。

如果一个数组太长,则NumPy自动省略中间部分而只打印两端的数据。

可通过设置printoptions参数来禁用NumPy的这种行为并强制打印整个数组:

import numpy as np

def test():

	print np.arange(10000)
	print '******'
	print np.arange(10000).reshape(100,100)
	print '******'
	np.set_printoptions(threshold='nan')  # 全部输出
	print np.arange(10000).reshape(100, 100)

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[   0    1    2 ..., 9997 9998 9999]
******
[[   0    1    2 ...,   97   98   99]
 [ 100  101  102 ...,  197  198  199]
 [ 200  201  202 ...,  297  298  299]
 ..., 
 [9700 9701 9702 ..., 9797 9798 9799]
 [9800 9801 9802 ..., 9897 9898 9899]
 [9900 9901 9902 ..., 9997 9998 9999]]
******
[[   0    1    2    3    4    5    6    7    8    9   10   11   12   13
    14   15   16   17   18   19   20   21   22   23   24   25   26   27
    28   29   30   31   32   33   34   35   36   37   38   39   40   41
    42   43   44   45   46   47   48   49   50   51   52   53   54   55
    56   57   58   59   60   61   62   63   64   65   66   67   68   69
    70   71   72   73   74   75   76   77   78   79   80   81   82   83
    84   85   86   87   88   89   90   91   92   93   94   95   96   97
    98   99]
 [ 100  101  102  103  104  105  106  107  108  109  110  111  112  113
   114  115  116  117  118  119  120  121  122  123  124  125  126  127
   128  129  130  131  132  133  134  135  136  137  138  139  140  141
   142  143  144  145  146  147  148  149  150  151  152  153  154  155
   156  157  158  159  160  161  162  163  164  165  166  167  168  169
   170  171  172  173  174  175  176  177  178  179  180  181  182  183
   184  185  186  187  188  189  190  191  192  193  194  195  196  197
   198  199]
 [ 200  201  202  203  204  205  206  207  208  209  210  211  212  213
   214  215  216  217  218  219  220  221  222  223  224  225  226  227
   228  229  230  231  232  233  234  235  236  237  238  239  240  241
   242  243  244  245  246  247  248  249  250  251  252  253  254  255
   256  257  258  259  260  261  262  263  264  265  266  267  268  269
...

1、数组属性

在NumPy中,维度称为axis,axis的数量叫做rank

NumPy的数组中比较重要ndarray对象属性有:

  • ndarray.ndim:数组的axis(维)的数量。在Python中,维的数量被称作rank。

  • ndarray.shape:数组的各个维(注意和维和维数要区分开)。它是一个数组各个维的长度构成的整数元组。对n行m列矩阵而言,shape将是(n,m)。因此,shape元组的长度也就是rank,也是维数ndim。

  • ndarray.size:数组元素的总个数,等于shape属性中元组元素的乘积。

  • ndarray.dtype:表示数组中元素类型的对象,可使用标准的Python类型创建或指定dtype。此外,NumPy还提供了其自有的类型,比如numpy.int32, numpy.int16, numpy.float64。

  • ndarray.itemsize:数组各元素的占多少字节。例如,一个元素类型为float64的数组itemsiz属性值为8(float64占用64个bits,每个字节长度为8,所以64/8,占用8个字节),又如,一个元素类型为complex32的数组item属性为4(32/8)。ndarray.itemsize等于ndarray.dtype.itemsize。

  • ndarray.data:装载数组真实元素的缓冲区。通常,我们用不到这个属性,因为我们一般使用索引访问数组元素。

示例:

import numpy as np

def test():

	a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
	b = np.array(a)
	print b
	print u'维数是:', b.ndim
	print u'维度是:', b.shape
	print u'元素总个数是:', b.size
	print u'元素的数据类型是:', b.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
维数是: 2
维度是: (3L, 3L)
元素总个数是: 9
元素的数据类型是: int32

numpy中基本的数据类型有:

NumPy中的基本数据类型
名称 描述
bool 用一个字节存储的布尔类型(True或False)
inti 由所在平台决定其大小的整数(一般为int32或int64)
int8 一个字节大小,-128 至 127
int16 整数,-32768 至 32767
int32 整数,-2 ** 31 至 2 ** 32 -1
int64 整数,-2 ** 63 至 2 ** 63 - 1
uint8 无符号整数,0 至 255
uint16 无符号整数,0 至 65535
uint32 无符号整数,0 至 2 ** 32 - 1
uint64 无符号整数,0 至 2 ** 64 - 1
float16 半精度浮点数:16位,正负号1位,指数5位,精度10位
float32 单精度浮点数:32位,正负号1位,指数8位,精度23位
float64或float 双精度浮点数:64位,正负号1位,指数11位,精度52位
complex64 复数,分别用两个32位浮点数表示实部和虚部
complex128或complex 复数,分别用两个64位浮点数表示实部和虚部

2、创建数组

创建数组的方法有很多。

2.1 使用python列表或元组创建

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

参数:

  • object : 是一个array_like象,包括list,tuple等__array__定制类可以返回类数组的对象。
  • dtype:数据类型,默认为可以保存数据的最小类型,可以制定
  • 其他的参数可以通过help来查看。

使用array函数从常规的Python列表和元组创造数组。所创建的数组类型由原序列中的元素类型推导而来。注意:不能使用多个数值作为参数调用array。

import numpy as np

def test():

	a = [1, 2, 3]
	b = (2.1, 3.1, 4.1)
	an = np.array(a)
	bn = np.array(b)
	cn = np.array([3.25, 4.25, 5.25])
	dn = np.array((4.0, 5.0, 6.0))
	# en = np.array(5, 6, 7) #报错
	print an, an.dtype
	print bn, bn.dtype
	print cn, cn.dtype
	print dn, dn.dtype
	# print en

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[1 2 3] int32
[ 2.1  3.1  4.1] float64
[ 3.25  4.25  5.25] float64
[ 4.  5.  6.] float64

可使用双重序列来表示二维的数组,三重序列表示三维数组,以此类推。

import numpy as np
def test(): an = np.array([[1, 2, 3], [2, 3, 4]]) bn = np.array([(1, 2, 3), (2, 3, 4)]) cn = np.array(([1, 2, 3], [2, 3, 4])) dn = np.array([(1, 2, 3), [2, 3, 4]]) en = np.array([((1, 2), [2, 3]), [[2, 3], (3, 4)]]) print an print '******' print bn print '******' print cn print '******' print dn print '******' print en def main(): pass if __name__ == '__main__': #main() test() 输出: [[1 2 3] [2 3 4]] ****** [[1 2 3] [2 3 4]] ****** [[1 2 3] [2 3 4]] ****** [[1 2 3] [2 3 4]] ****** [[[1 2] [2 3]] [[2 3] [3 4]]]

可以在创建时显式指定数组中元素的类型:

import numpy as np

def test():
	an = np.array([[1, 2], [3, 4]], dtype=complex)
	bn = np.array([(1, 2), (3, 4)], dtype=int)
	cn = np.array(((1, 2), (3, 4)), dtype=float)
	print an, an.dtype
	print '******'
	print bn, bn.dtype
	print '******'
	print cn, cn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[ 1.+0.j  2.+0.j]
 [ 3.+0.j  4.+0.j]] complex128
******
[[1 2]
 [3 4]] int32
******
[[ 1.  2.]
 [ 3.  4.]] float64

2.2 占位符创建

通常,刚开始时数组的元素未知,而数组的大小已知。因此,NumPy提供了一些使用占位符创建数组的函数(可以自己制定数组中元素的类型)。这些函数有助于满足除了数组扩展的需要,同时降低了高昂的运算开销。默认创建的数组类型(dtype)都是float64

numpy.zeros(shape, dtype=float, order=’C’)

参数:

  • shape:int或int类型序列,表示矩阵形状(可以是列表,可以是元组,也可以是单个数字
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主

给定要求下的0矩阵。

示例:

import numpy as np

def test():

	an = np.zeros((2, 3, 4))
	bn = np.zeros((2, 3, 4), dtype=int)
	cn = np.zeros((2, 3, 4), dtype=np.int)
	print an, an.dtype
	print '******'
	print bn, bn.dtype
	print '******'
	print cn, cn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]] float64
******
[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]] int32
******
[[[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]

 [[0 0 0 0]
  [0 0 0 0]
  [0 0 0 0]]] int32

numpy.zeros_like(a, dtype=None, order=’K’, subok=True)

参数:

  • a:返回值仿照的矩阵
  • dtype:输出的数据类型
  • order:‘C’ 、 ‘F’、 ‘A’、 ‘K’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主,‘A’表示以列为主存储,如果a是列相邻的,‘K’表示尽可能与a的存储方式相同
  • subok:bool类型,True:使用a的内部数据类型,False:使用a数组的数据类型

生成与a相似(形状、数据类型)的零矩阵。

示例:

import numpy as np

def test():

	an = np.arange(6)
	an = an.reshape((2, 3))
	bn = np.zeros_like(an)
	print an, an.dtype, an.shape
	print '******'
	print bn, bn.dtype, an.shape

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[0 1 2]
 [3 4 5]] int32 (2L, 3L)
******
[[0 0 0]
 [0 0 0]] int32 (2L, 3L)

numpy.ones(shape, dtype=None, order=’C’)

参数:

  • shape:int或int类型序列,表示矩阵形状
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主

给定要求下的单位矩阵。

numpy.ones_like(a, dtype=None, order=’K’, subok=True)

参数:

  • a:返回值仿照的矩阵
  • dtype:输出的数据类型
  • order:‘C’ 、 ‘F’、 ‘A’、 ‘K’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主,‘A’表示以列为主存储,如果a是列相邻的,‘K’表示尽可能与a的存储方式相同
  • subok:bool类型,True:使用a的内部数据类型,False:使用a数组的数据类型

生成与a相似(形状、数据类型)的单位矩阵。

numpy.empty(shape, dtype=float, order=’C’)
参数:

  • shape:int或int类型元组,表示矩阵形状
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主

生成随机矩阵,numpy.enpty()只分配数组所使用的内存,不对数据初始化起作用。

numpy.empty_like(a, dtype=None, order=’K’, subok=True)

参数:

  • a:返回值仿照的矩阵
  • dtype:输出的数据类型
  • order:‘C’ 、 ‘F’、 ‘A’、 ‘K’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主,‘A’表示以列为主存储,如果a是列相邻的,‘K’表示尽可能与a的存储方式相同
  • subok:bool类型,True:使用a的内部数据类型,False:使用a数组的数据类型

生成与a相似(形态和数据类型)的随机矩阵。

numpy.eye(N, M=None, k=0, dtype=float)

参数:

  • N:行数
  • M:列数
  • k:对角线偏移
  • dtype:输出的数据类型

对角矩阵(主对角线上元素都为1,其他元素都为0)——对角线向右上方偏移k(k>0向右上方偏移,k<0向左下方偏移)。

示例:

import numpy as np

def test():

	an = np.eye(2)
	bn = np.eye(3, k=1, dtype=int)
	cn = np.eye(5, k=-2, dtype=float)
	dn = np.eye(5, M=3, k=-2, dtype=np.float)
	print an, an.dtype
	print '******'
	print bn, bn.dtype
	print '******'
	print cn, cn.dtype
	print '******'
	print dn, dn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[ 1.  0.]
 [ 0.  1.]] float64
******
[[0 1 0]
 [0 0 1]
 [0 0 0]] int32
******
[[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]] float64
******
[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]] float64

numpy.full(shape, fill_value, dtype=None, order=’C’)

参数:

  • shape:int或int类型序列,表示矩阵形状
  • fill_value:填充值
  • dtype:输出的数据类型
  • order:‘C’ 或者 ‘F’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主

给定要求(形状、数据类型)填充的矩阵。

示例:

import numpy as np

def test():

	an = np.full((2, 2), 0.1, dtype=int)
	bn = np.full((2, 2), 10)
	print an, an.dtype
	print '******'
	print bn, bn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
[[0 0]
 [0 0]] int32
  format(shape, fill_value, array(fill_value).dtype), FutureWarning)
******
[[ 10.  10.]
 [ 10.  10.]] float64

numpy.full_like(a, fill_value, dtype=None, order=’K’, subok=True)

参数:

  • a:返回值仿照的矩阵
  • fill_value:填充值
  • dtype:输出的数据类型
  • order:‘C’ 、 ‘F’、 ‘A’、 ‘K’,表示数组在内存的存放次序是以行(C)为主还是以列(F)为主,‘A’表示以列为主存储,如果a是列相邻的,‘K’表示尽可能与a的存储方式相同
  • subok:bool类型,True:使用a的内部数据类型,False:使用a数组的数据类型

生成与a相似(形状、数据类型)的fill_value填充的矩阵。

示例:

import numpy as np

def test():

	an = np.array([1, 2, 3, 4, 5], dtype=float)
	an1 = np.arange(6, dtype=int)
	bn = np.full_like(an, 0.1)
	cn = np.full_like(an, 2.5, dtype=int)
	dn = np.full_like(an, 1)
	en = np.full_like(an, 5, dtype=float)
	fn = np.full_like(an1, 2.5)
	gn = np.full_like(an1, 5, dtype=float)
	hn = np.full_like(an1, 2.5, dtype=int)

	print 'an:', an, an.dtype
	print '******'
	print 'bn:', bn, bn.dtype
	print '******'
	print 'cn:', cn, cn.dtype
	print '******'
	print 'dn:', dn, dn.dtype
	print '******'
	print 'en:', en, en.dtype
	print '******'
	print 'an1:', an1, an1.dtype
	print '******'
	print 'fn:', fn, fn.dtype
	print '******'
	print 'gn:', gn, gn.dtype
	print '******'
	print 'hn:', hn, hn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
an: [ 1.  2.  3.  4.  5.] float64
******
bn: [ 0.1  0.1  0.1  0.1  0.1] float64
******
cn: [2 2 2 2 2] int32
******
dn: [ 1.  1.  1.  1.  1.] float64
******
en: [ 5.  5.  5.  5.  5.] float64
******
an1: [0 1 2 3 4 5] int32
******
fn: [2 2 2 2 2 2] int32
******
gn: [ 5.  5.  5.  5.  5.  5.] float64
******
hn: [2 2 2 2 2 2] int32

numpy.identity(n, dtype=None)

参数:

  • n:行数(也是列数)
  • dtype:输出的数据类型

n*n对角矩阵(主对角线上元素都为1,其他元素都为0)。

numpy.arange([start,]stop[,step],dtype=None) 

类似于range,通过指定开始值,终值和步长来创建表示等差数列的一维数组,注意该函数和range一样结果不包含终值。 其中start参数如果省略,则表示从0开始,step省略,则表示步长为1。

 示例:

import numpy as np

def test():

	an = np.arange(5)
	anf = np.arange(5, dtype=float)
	bn = np.arange(5.5)
	bni = np.arange(5.5, dtype=int)
	cn = np.arange(1, 5, 0.5)
	cni = np.arange(1, 5, 0.5, dtype=int)
	dn = np.arange(1, 5.5, 1)
	dnf = np.arange(1, 5.5, 1, dtype=float)
	print 'an:', an, an.dtype
	print '******'
	print 'anf:', anf, anf.dtype
	print '******'
	print 'bn:', bn, bn.dtype
	print '******'
	print 'bni:', bni, bni.dtype
	print '******'
	print 'cn:', cn, cn.dtype
	print '******'
	print 'cni:', cni, cni.dtype
	print '******'
	print 'dn:', dn, dn.dtype
	print '******'
	print 'dnf:', dnf, dnf.dtype


def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
an: [0 1 2 3 4] int32
******
anf: [ 0.  1.  2.  3.  4.] float64
******
bn: [ 0.  1.  2.  3.  4.  5.] float64
******
bni: [0 1 2 3 4 5] int32
******
cn: [ 1.   1.5  2.   2.5  3.   3.5  4.   4.5] float64
******
cni: [1 1 1 1 1 1 1 1] int32
******
dn: [ 1.  2.  3.  4.  5.] float64
******
dnf: [ 1.  2.  3.  4.  5.] float64

arange使用浮点数参数时,由于浮点数精度有限,通常无法预测获得的元素个数。因此,最好使用函数linspace去接收我们想要的元素个数来代替用range来指定步长。

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

参数:

start,stop是开始,结束的数字;

num是生成多少个数字,默认50个,必须是非负;

endpoint是最后一个stop数字是否包含进去,默认包含;

retstep,是两个数字间的间距,默认不显示;

dtype默认。

在指定的间隔内返回均匀间隔的数字。返回num均匀分布的样本,在[start, stop]。这个区间的端点可以任意的被排除在外。

示例:

import numpy as np

def test():

	an = np.linspace(0, 5, 5)
	bn = np.linspace(0, 5, 5, endpoint=False)
	cn = np.linspace(0, 5, 5, retstep=True)
	dn = np.linspace(0, 5, 5, dtype=np.int8)
	#dn = np.linspace(0, 5, 5, dtype=int8) # 报错
	print 'an:', an, an.dtype
	print '******'
	print 'bn:', bn, bn.dtype
	print '******'
	print 'cn:', cn, cn[0].dtype, type(cn[1])
	print '******'
	print 'dn:', dn, dn.dtype

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
an: [ 0.    1.25  2.5   3.75  5.  ] float64
******
bn: [ 0.  1.  2.  3.  4.] float64
******
cn: (array([ 0.  ,  1.25,  2.5 ,  3.75,  5.  ]), 1.25) float64 <type 'float'>
******
dn: [0 1 2 3 5] int8

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

参数:

base意思是指数的基数;

该函数与np.linspace类似,不过它生成的数组是等比数列,基数默认为10。

numpy.fromfunction()

可以从指定的函数中生成数组,第一个参数是函数名称,第二个参数是数组形状。

示例:

3、axis

axis不太好理解,基础要点有:

(1)axis=0表示最外层,1,2,...依次往里;

(2)假设数组an有m维,即an.shape=(s_0,s_1,s_2,...,s_i-1,   s_i=k,   s_i+1,...,s_m-3,s_m-2,s_m-1)。axis=i时,假设第i维的长度为k(即s_i=k),则可以理解为i以外的层固定了一个个的位置(共s_0*s_1*...*s_i-1个位置),而每个位置有k块模板,每块模板均为shape=(s_i+1,...,s_m-3,s_m-2,s_m-1)的数组。指定axis=i进行操作时,等价于针对每个位置,分别将k块模板合并成一块模板,合并的过程是按取k块模板的相同位置的值(k个),做指定的操作,得到的结果便是新模板的相同位置的值。新数组的维度变成(s_0,s_1,s_2,...,s_i-1,   1,   s_i+1,...,s_m-3,s_m-2,s_m-1)。

示例(4维):

import numpy as np

def test():

	ln = np.linspace(1, 16, 16)
	an = ln.reshape((2, 2, 2, 2))
	print '***Original***'
	print an, an.shape
	s0 = np.sum(an, axis=0)
	print '***axis=0***'
	print s0, s0.shape
	s1 = np.sum(an, axis=1)
	print '***axis=1***'
	print s1, s1.shape
	s2 = np.sum(an, axis=2)
	print '***axis=2***'
	print s2, s2.shape
	s3 = np.sum(an, axis=3)
	print '***axis=3***'
	print s3, s3.shape

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
***Original***
[[[[  1.   2.]
   [  3.   4.]]

  [[  5.   6.]
   [  7.   8.]]]


 [[[  9.  10.]
   [ 11.  12.]]

  [[ 13.  14.]
   [ 15.  16.]]]] (2L, 2L, 2L, 2L)
***axis=0***
[[[ 10.  12.]
  [ 14.  16.]]

 [[ 18.  20.]
  [ 22.  24.]]] (2L, 2L, 2L)
***axis=1***
[[[  6.   8.]
  [ 10.  12.]]

 [[ 22.  24.]
  [ 26.  28.]]] (2L, 2L, 2L)
***axis=2***
[[[  4.   6.]
  [ 12.  14.]]

 [[ 20.  22.]
  [ 28.  30.]]] (2L, 2L, 2L)
***axis=3***
[[[  3.   7.]
  [ 11.  15.]]

 [[ 19.  23.]
  [ 27.  31.]]] (2L, 2L, 2L)

示例(5维):

import numpy as np

def test():

	ln = np.linspace(1, 32, 32)
	an = ln.reshape((2, 2, 2, 2, 2))
	print '***Original***'
	print an, an.shape
	s0 = np.sum(an, axis=0)
	print '***axis=0***'
	print s0, s0.shape
	s1 = np.sum(an, axis=1)
	print '***axis=1***'
	print s1, s1.shape
	s2 = np.sum(an, axis=2)
	print '***axis=2***'
	print s2, s2.shape
	s3 = np.sum(an, axis=3)
	print '***axis=3***'
	print s3, s3.shape
	s4 = np.sum(an, axis=4)
	print '***axis=4***'
	print s4, s4.shape

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
***Original***
[[[[[  1.   2.]
    [  3.   4.]]

   [[  5.   6.]
    [  7.   8.]]]


  [[[  9.  10.]
    [ 11.  12.]]

   [[ 13.  14.]
    [ 15.  16.]]]]



 [[[[ 17.  18.]
    [ 19.  20.]]

   [[ 21.  22.]
    [ 23.  24.]]]


  [[[ 25.  26.]
    [ 27.  28.]]

   [[ 29.  30.]
    [ 31.  32.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=0***
[[[[ 18.  20.]
   [ 22.  24.]]

  [[ 26.  28.]
   [ 30.  32.]]]


 [[[ 34.  36.]
   [ 38.  40.]]

  [[ 42.  44.]
   [ 46.  48.]]]] (2L, 2L, 2L, 2L)
***axis=1***
[[[[ 10.  12.]
   [ 14.  16.]]

  [[ 18.  20.]
   [ 22.  24.]]]


 [[[ 42.  44.]
   [ 46.  48.]]

  [[ 50.  52.]
   [ 54.  56.]]]] (2L, 2L, 2L, 2L)
***axis=2***
[[[[  6.   8.]
   [ 10.  12.]]

  [[ 22.  24.]
   [ 26.  28.]]]


 [[[ 38.  40.]
   [ 42.  44.]]

  [[ 54.  56.]
   [ 58.  60.]]]] (2L, 2L, 2L, 2L)
***axis=3***
[[[[  4.   6.]
   [ 12.  14.]]

  [[ 20.  22.]
   [ 28.  30.]]]


 [[[ 36.  38.]
   [ 44.  46.]]

  [[ 52.  54.]
   [ 60.  62.]]]] (2L, 2L, 2L, 2L)
***axis=4***
[[[[  3.   7.]
   [ 11.  15.]]

  [[ 19.  23.]
   [ 27.  31.]]]


 [[[ 35.  39.]
   [ 43.  47.]]

  [[ 51.  55.]
   [ 59.  63.]]]] (2L, 2L, 2L, 2L)

示例(6维):

import numpy as np

def test():

	ln = np.linspace(1, 64, 64)
	an = ln.reshape((2, 2, 2, 2, 2, 2))
	print '***Original***'
	print an, an.shape
	s0 = np.sum(an, axis=0)
	print '***axis=0***'
	print s0, s0.shape
	s1 = np.sum(an, axis=1)
	print '***axis=1***'
	print s1, s1.shape
	s2 = np.sum(an, axis=2)
	print '***axis=2***'
	print s2, s2.shape
	s3 = np.sum(an, axis=3)
	print '***axis=3***'
	print s3, s3.shape
	s4 = np.sum(an, axis=4)
	print '***axis=4***'
	print s4, s4.shape
	s5 = np.sum(an, axis=5)
	print '***axis=5***'
	print s5, s5.shape

def main():

	pass

if __name__ == '__main__':

	#main()
	test()

输出:
***Original***
[[[[[[  1.   2.]
     [  3.   4.]]

    [[  5.   6.]
     [  7.   8.]]]


   [[[  9.  10.]
     [ 11.  12.]]

    [[ 13.  14.]
     [ 15.  16.]]]]



  [[[[ 17.  18.]
     [ 19.  20.]]

    [[ 21.  22.]
     [ 23.  24.]]]


   [[[ 25.  26.]
     [ 27.  28.]]

    [[ 29.  30.]
     [ 31.  32.]]]]]




 [[[[[ 33.  34.]
     [ 35.  36.]]

    [[ 37.  38.]
     [ 39.  40.]]]


   [[[ 41.  42.]
     [ 43.  44.]]

    [[ 45.  46.]
     [ 47.  48.]]]]



  [[[[ 49.  50.]
     [ 51.  52.]]

    [[ 53.  54.]
     [ 55.  56.]]]


   [[[ 57.  58.]
     [ 59.  60.]]

    [[ 61.  62.]
     [ 63.  64.]]]]]] (2L, 2L, 2L, 2L, 2L, 2L)
***axis=0***
[[[[[ 34.  36.]
    [ 38.  40.]]

   [[ 42.  44.]
    [ 46.  48.]]]


  [[[ 50.  52.]
    [ 54.  56.]]

   [[ 58.  60.]
    [ 62.  64.]]]]



 [[[[ 66.  68.]
    [ 70.  72.]]

   [[ 74.  76.]
    [ 78.  80.]]]


  [[[ 82.  84.]
    [ 86.  88.]]

   [[ 90.  92.]
    [ 94.  96.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=1***
[[[[[  18.   20.]
    [  22.   24.]]

   [[  26.   28.]
    [  30.   32.]]]


  [[[  34.   36.]
    [  38.   40.]]

   [[  42.   44.]
    [  46.   48.]]]]



 [[[[  82.   84.]
    [  86.   88.]]

   [[  90.   92.]
    [  94.   96.]]]


  [[[  98.  100.]
    [ 102.  104.]]

   [[ 106.  108.]
    [ 110.  112.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=2***
[[[[[  10.   12.]
    [  14.   16.]]

   [[  18.   20.]
    [  22.   24.]]]


  [[[  42.   44.]
    [  46.   48.]]

   [[  50.   52.]
    [  54.   56.]]]]



 [[[[  74.   76.]
    [  78.   80.]]

   [[  82.   84.]
    [  86.   88.]]]


  [[[ 106.  108.]
    [ 110.  112.]]

   [[ 114.  116.]
    [ 118.  120.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=3***
[[[[[   6.    8.]
    [  10.   12.]]

   [[  22.   24.]
    [  26.   28.]]]


  [[[  38.   40.]
    [  42.   44.]]

   [[  54.   56.]
    [  58.   60.]]]]



 [[[[  70.   72.]
    [  74.   76.]]

   [[  86.   88.]
    [  90.   92.]]]


  [[[ 102.  104.]
    [ 106.  108.]]

   [[ 118.  120.]
    [ 122.  124.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=4***
[[[[[   4.    6.]
    [  12.   14.]]

   [[  20.   22.]
    [  28.   30.]]]


  [[[  36.   38.]
    [  44.   46.]]

   [[  52.   54.]
    [  60.   62.]]]]



 [[[[  68.   70.]
    [  76.   78.]]

   [[  84.   86.]
    [  92.   94.]]]


  [[[ 100.  102.]
    [ 108.  110.]]

   [[ 116.  118.]
    [ 124.  126.]]]]] (2L, 2L, 2L, 2L, 2L)
***axis=5***
[[[[[   3.    7.]
    [  11.   15.]]

   [[  19.   23.]
    [  27.   31.]]]


  [[[  35.   39.]
    [  43.   47.]]

   [[  51.   55.]
    [  59.   63.]]]]



 [[[[  67.   71.]
    [  75.   79.]]

   [[  83.   87.]
    [  91.   95.]]]


  [[[  99.  103.]
    [ 107.  111.]]

   [[ 115.  119.]
    [ 123.  127.]]]]] (2L, 2L, 2L, 2L, 2L)

3、排序

假设:

a = array([[ 2,  7,  4,  2],
           [35,  9,  1,  5],
           [22, 12,  35,  2]])

lexsort()

按第i列(以第3列为例),升序:

idex=np.lexsort([a[:,2]])
a_sort=a[idex,:]
print a_sort

[[35  9  1  5]
 [ 2  7  4  2]
 [22 12 35  2]]

按第i列(以第3列为例),降序:

idex=np.lexsort([-a[:,2]])
a_sort=a[idex,:]
print a_sort

[[22 12 35  2]
 [ 2  7  4  2]
 [35  9  1  5]]

按第i行(以第3行为例),升序:

idex=np.lexsort([a[2,:]])
a_sort=a[:,idex]
print a_sort

[[ 2  7  2  4]
 [ 5  9 35  1]
 [ 2 12 22 35]]

按第i行(以第3行为例),升序:

idex=np.lexsort([-a[2,:]])
a_sort=a[:,idex]
print a_sort

[[ 4  2  7  2]
 [ 1 35  9  5]
 [35 22 12  2]]

 argsort()函数

按第i列(以第3列为例),升序:

idex = np.argsort(a[:,2])
a_sort=a[idex,:]
print a_sort

按第i列(以第3列为例),降序:

idex = np.argsort(-a[:,2])
a_sort=a[idex,:]
print a_sort

按第i行(以第3行为例),升序:

idex = np.argsort(a[2,:])
a_sort=a[:,idex]
print a_sort

按第i行(以第3行为例),降序:

idex = np.argsort(-a[2,:])
a_sort=a[:,idex]
print a_sort

5、形变

 

6、numpy与list

 对于一维的array所有Python列表支持的下标相关的方法array也都支持

6.1 索引的区别

import numpy as np
a = [2.3, 3.2, 5.6, 3.9, 2.5, 8.2]
b = np.array(a)
index = [2, 3, 5]
print b[index]  # [ 5.6  3.9  8.2]
print a[index]  # TypeError: list indices must be integers, not list

7、广播

对于array,默认执行对位运算。涉及到多个array的对位运算需要array的维度一致,如果一个array的维度和另一个array的子维度一致,则在没有对齐的维度上分别执行对位运算,这种机制叫做广播(broadcasting)

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

b = np.array([
    [1, 2, 3],
    [1, 2, 3]
])

'''
维度一样的array,对位计算
array([[2, 4, 6],
       [5, 7, 9]])
'''
a + b

'''
array([[0, 0, 0],
       [3, 3, 3]])
'''
a - b

'''
array([[ 1,  4,  9],
       [ 4, 10, 18]])
'''
a * b

'''
array([[1, 1, 1],
       [4, 2, 2]])
'''
a / b

'''
array([[ 1,  4,  9],
       [16, 25, 36]])
'''
a ** 2

'''
array([[  1,   4,  27],
       [  4,  25, 216]])
'''
a ** b

c = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [10, 11, 12]
])
d = np.array([2, 2, 2])

'''
广播机制让计算的表达式保持简洁
d和c的每一行分别进行运算
array([[ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])
'''
c + d

'''
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18],
       [20, 22, 24]])
'''
c * d

'''
1和c的每个元素分别进行运算
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
'''
c - 1
原文地址:https://www.cnblogs.com/qjoanven/p/7681543.html