1.概览
numpy的主要对象是同种元素的多维数组。这是一个所有元素都是同一种类型、通过同一个正整数元组索引的元素表格(通常元素是数字)
维度(dimensions):轴
轴的个数:秩(rank)
例如,在3D空间一个点的坐标[1, 2, 3]是一个秩为1的数组,因为它只有一个轴。那个轴长度为3.又例如,在以下例子中,数组的秩为2(它有两个维度).第一个维度长度为2,第二个维度长度为3.
[[ 1., 0., 0.], [ 0., 1., 2.]]
数组类:ndarray(数组),注意
numpy.array
和标准Python
库类array.array
并不相同,后者只处理一维数组和提供少量功能。更多重要ndarray
对象属性有:- ndarray.ndim ——数组轴(秩)的个数
- ndarray.shape ——数组的维度;是一个指示数组在每个维度上大小的整数元组。例如一个
n排
m列的矩阵,它的
shape属性将是(2,3),这个元组的长度显然是秩,即维度或者
ndim属性 - ndarry.size——数组元素的总个数
- ndarray.dtype ——用来描述数组中元素类型的对象,可以通过创造或指定
dtype
使用标准Python
类型。另外Numpy提供它自己的数据类型。 - ndarray.itemsize ——数组中每个元素的字节大小。例如,一个元素类型为
float64
的数组itemsiz
属性值为8(=64/8),又如,一个元素类型为complex32
的数组item
属性为4(=32/8)
. - ndarray.data——包含实际数组元素的缓冲区,通常我们不需要使用这个属性,因为我们总是通过索引来使用数组中的元素
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# input1
from numpy import*
a = arrange(15).reshape(3,5)
print a
# output1
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
# input2
print a.shape
# output2
(3,5)
# in3
print a.ndim
# out3
2
# in4
print a.dtype.name
# out4
'int64'
# in5
print a.itemsize
# out5
8
# in6
print a.size
# in7
print tyep(a)
# out7
numpy.ndarray
# in8
b = array([6, 7, 8])
b
# out8
array([6,7,8])
# in9
print type(b)
# out
numpy.ndarray
2.创建数组
使用array函数从常规的python列表和元组创造数组,所创建的数组类型由原序列中的元素类型推导而来。
1 | # create array |
3.打印数组
当打印数组时,numpy会以类似嵌套列表的形式显示,呈以下布局
- 最后的轴从左到右打印
- 次后的轴从顶向下打印
- 剩下的轴从顶向下打印,每个切片通过一个空行与下一个隔开
一维数组被打印成行,二维数组组成矩阵,三维数组组成矩阵列表
1
2
3
4
5
6
7
8
9
10# print array
a = arange(6) # 1d array
print (a)
b = arange(12).reshape(4,3) # 2d array
print (b)
c = arange(24).reshape(2,3,4) # 3d array
print (c)
print (arange(10000))
print (arange(10000).reshape(100,100))
set_printoptions(threshold='nan') # 设置printoptions参数更改打印选项
4.基本运算
数组的算术运算是按元素的。新的数组被创建并且被结果填充。
1 | # basic operation |
5.通用函数ufunc
5.1 函数
numpy提供常见的数学函数如sin,cos,exp,其统称为通用函数ufunc,在numpy里这些函数作用按数组的元素运算,产生一个数组作为输出。
其他函数:all, alltrue, any, apply along axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj, conjugate, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor, inner, inv, lexsort, max, maximum, mean, median, min, minimum, nonzero, outer, prod, re, round, sometrue, sort, std, sum, trace, transpose, var, vdot, vectorize, where
1 | # ufunc |
5.2 索引、切片和迭代
一维数组可被索引、切片和迭代,如同列表和其他python序列。
b[i]中括号中的表达式被当作i和一系列:,来代表剩下的轴。NumPy也允许你使用“点”像b[i,…]。
点(…)代表许多产生一个完整的索引元组必要的分号。如果x是秩为5的数组(即它有5个轴),那么:
x[1,2,…]
等同于x[1,2,:,:,:]
x[…,3]
等同于x[:,:,:,:,3]
x[4,…,5,:]
等同于x[4,:,:,5,:]
1
2
3
4
5
6> # c = array( [ [[ 0, 1, 2], # a 3D array (two stacked 2D arrays) ... [ 10, 12, 13]]...
> # [[100,101,102], ... [110,112,113]] ] )
> # c.shape (2, 2, 3)
> # c[1,...] # same as c[1,:,:] or c[1] array([[100, 101, 102], [110, 112, 113]])
> # c[...,2] # same as c[:,:,2] array([[ 2, 13], [102, 113]])
>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# ufunc
B = arange(3)
print B
print exp(B)
print sqrt(B)
C = array([2.,-1.,4.])
print add(B,C)
# 索引,切片和迭代
print B[2] # output the third element of B
print B[0:2]
a[:6:2] = -1000
print a
print a[::-1] # reversied a
# 多维数组可以每个轴有一个索引。这些索引由一个逗号分割的元组给出
def f(x,y):
return 10*x+y
b = fromfunction(f,(5,4),dtype=int)
print b
c = fromfunction(f,(3,3),dtype=float)
print c
print b[2,3]
print b[1,1]
print b[0:5,1]
print b[0:4,0]
print b[:,1]
print b[:,2]
print b[1:3,2]
# 当少于轴数的索引被提供时,确失的索引被认为是整个切片
print b[-1]
# 迭代多维数组是就第一个轴而言的
for row in b:
print (row)
for column in b:
print (column)
# 如果一个人想对每个数组中元素进行运算,我们可以使用flat属性,该属性是数组元素的一个迭代器
for element in b.flat:
print (element,end=",")
6.形状操作
6.1 更改数组的形状
一个数组的形状由其每个轴上的元素个数给出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15# shape operation
a = floor(10*random.random((3,4)))
print a
print a.shape
print a.ravel() # flatten the array
a.shape = (6,2)
print a.transpose() # 矩阵转置transpose
a.shape = (2,6)
print a.transpose()
# reshape函数改变参数形状并返回它,而resize函数改变数组自身
print a
a.resize((2,6))
print a
# 如果在改变形状操作中一个维度被给做-1,其维度将自动被计算
6.2 组合(stack)不同的数组
几种不同方法可沿不同轴将数组堆叠在一起。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# stack different arrays
a = floor(10*random.random((2,2)))
print a
b = floor(10*random.random((2,2)))
print b
print vstack((a,b)) # 将a和b纵向组合在一起
print hstack((a,b)) # 将a和b横向组合在一起
# 函数column_stack以列将一维数组合成二维数组,它等同与vstack对一维数组
print column_stack((a,b)) # # With 2D arrays
a = array([4.,2.])
b = array([2.,8.])
print a[:,newaxis] # This allows to have a 2D columns vector
print column_stack((a[:,newaxis],b[:,newaxis]))
print vstack((a[:,newaxis],b[:,newaxis])) #The behavior of vstack is different
# row_stack函数,另一方面,将一维数组以行组合成二维数组
# 对那些维度比二维更高的数组,hstack沿着第二个轴组合,vstack沿着第一个轴组合,concatenate允许可选参数给出组合时沿着的轴
# 在复杂情况下,r_[]和c_[]对创建沿着一个方向组合的数很有用,它们允许范围符号(“:”):
print r_[1:4,0,4]
# 当使用数组作为参数时,r_和c_的默认行为和vstack和hstack很像,但是允许可选的参数给出组合所沿着的轴的代号。
# 函数:hstack, vstack, column_stack, row_stack, concatenate, c_, r_
6.3 将一个数组分割(split)成几个小数组
使用
hsplit
你能将数组沿着它的水平轴分割,或者指定返回相同形状数组的个数,或者指定在哪些列后发生分割:
1 | # split an array into several pieces |
6.4 复制和视图
当运算和处理数据时,它们的数据有时被拷贝到新的数组有时不是。这有三种情况:
1.完全不拷贝:简单的赋值不拷贝数据对象或其数据
2.视图view和浅复制:不同的数组对象分享同一个数据,视图方法创造一个新的数组对象指向同一数据
3.深复制:完全赋值数据及其数据
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
34copy and view
# 1.totally not copied
a = arange(12)
b = a
print b is a
b.shape = 3,4 # change the shape of a
print a.shape
# Python 传递不定对象作为参考,所以函数调用不拷贝数组
def f(x):
print (id(x))
print f(a)
# 2.view and shadow copy
# 不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据,数据其实是存在源数组的
c = a.view()
print c is a
print c.base is a # c is a vie of the data owned by a
print c.flags.owndata # judge,c has no data
c.shape = 2,6
print a.shape # chage c's shape but a's shape goesnbt change
c[0,4] = 1234
print a # a's data changes
# 切片数组返回它的一个视图:
s = a[:,1:3] # spaces added for clarity; could also be written "s = a[:,1:3]"
s[:] = 10 # # s[:] is a view of s. Note the difference between s=10 and s[:]=10
print a
# 3.deep copy
d = a.copy() # a new array object with new data is created
d is a
print d is a
print d.base is a # d doesn't share anything with a
d[0,0] = 9999
print a
7.函数和方法method总览
这是个numpy函数和方法分类排列目录,这些名字链接到numpy示例,可看到函数是起作用的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23# 1.创建数组
arrange, array, copy, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r, zeros, zeros_like
# 2.转化
astype, atleast ld, atleast 2d, atleast 3d, mat
# 3.操作
array split, column stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, item, newsxis,ravel, repeat, reshape, resize, squeeze,swapaxes, take,transpose
# 4.询问
all, any, nonzero, where
# 5.排序
argmax, argmin, argsort, max, min, ptp, searchsorted, sort
# 6.运算
choose, compress, cumprod, cumsum, inner, fill, imag, prod, putmask, real, sum
# 7.基本统计
cov, mean, std, var
# 8.基本线性代数
cross, dot, outer, svd, vdot