一、Numpy是什么?
- 1.Numrical Python,数值的Python,应用于数值分析领域的Python语言工具;
- 2.Numpy是一个开源的科学计算库;
- 3.Numpy弥补了作为通用编程语言的Python在数值计算方面,能力弱,速度慢的不足;
- 4.Numpy拥有丰富的数学函数、强大的多维数组和优异的运算性能;
- 5.Numpy与Scipy、scikit、matplotlib等其它科学计算库可以很好地协调工作;
- 6.Numpy可以取代matlab等工具,允许用户进行快速开发的同时完成交互式的原型设计。
python 和 numpy 在运算上的耗时对比:
import datetime as dt
import numpy as np
n = 100000
start = dt.datetime.now()
A, B = [], []
for i in range(n):
A.append(i ** 2)
B.append(i ** 3)
C = []
for a, b in zip(A, B):
C.append(a + b)
print("python耗时:", (dt.datetime.now() - start).microseconds)
start = dt.datetime.now()
C = np.arange(n) ** 2 + np.arange(n) ** 3
print("numpy耗时:", (dt.datetime.now() - start).microseconds)
python耗时: 101686
numpy耗时: 3372
二、多维数组
1.numpy.ndarray
numpy中的多维数组是numpy.ndarray类类型的对象,可用于表示数据结构中的任意维度的数组;
2.创建多维数组对象
numpy.arange(起始, 终止, 步长)->一维数组,首元素就是起始值,尾元素为终止值之前的最后一个元素,步长即每次递增的公差。缺省起始值为0,缺省步长为1。
numpy.array(任何可被解释为数组的容器)
3.内存连续,元素同质。
4.ndarray.dtype属性
表示元素的数据类型。通过dtype参数和astype()方法可以指定和修改元素的数据类型。
5.ndarray.shape属性
表示数组的维度:(高维度数, ..., 低维度数)
import numpy as np
a = np.arange(10)
print(a)
b = np.arange(1, 10)
print(b)
c = np.arange(1, 10, 2)
print(c)
d = np.array([])
print(d)
e = np.array([10, 20, 30, 40, 50])
print(e)
f = np.array([
[1, 2, 3],
[4, 5, 6]])
print(f)
print(type(f))
print(type(f[0][0]))
print(f.dtype)
g = np.array(['1', '2', '3'], dtype=np.int32)
print(type(g[0]))
print(g.dtype)
h = g.astype(np.str_)
print(type(h[0]))
print(h.dtype)
print(e.shape)
print(f.shape)
i = np.array([
[np.arange(1, 5), np.arange(5, 9), np.arange(9, 13)],
[np.arange(13, 17), np.arange(17, 21), np.arange(21, 25)]])
print(i.shape)
print(i)
[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]
[]
[10 20 30 40 50]
[[1 2 3]
[4 5 6]]
<class 'numpy.ndarray'>
<class 'numpy.int64'>
int64
<class 'numpy.int32'>
int32
<class 'numpy.str_'>
<U11
(5,)
(2, 3)
(2, 3, 4)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
6.元素索引,从0开始
数组[索引]
数组[行索引][列索引]
数组[页索引][行索引][列索引]
数组[页索引, 行索引, 列索引]
import numpy as np
a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(a)
print(a[0])
print(a[0][0])
print(a[0][0][0])
for i in range(a.shape[0]):
for j in range(a.shape[1]):
for k in range(a.shape[2]):
print(a[i][j][k], a[i, j, k])
b = np.array([1, 2, 3], dtype=int) # int->np.int32
print(b.dtype)
c = b.astype(float) # float->np.float64
print(c.dtype)
d = c.astype(str) # str->np.str_
print(d.dtype)
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[[1 2]
[3 4]]
[1 2]
1
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
int64
float64
<U32
7.numpy的内置类型和自定义类型
1)numpy的内置类型
bool_ 1字节布尔型,True(1)/False(0)
int8 1字节有符号整型,-128 - 127
int16 2字节有符号整型
int32 4字节有符号整型
int64 8字节有符号整型
uint8 1字节无符号整型,0 - 255
uint16 2字节无符号整型
uint32 4字节无符号整型
uint64 8字节无符号整型
float16 2字节浮点型
float32 4字节浮点型
float64 8字节浮点型
complex64 8字节复数型
complex128 16字节复数型
str_ 字符串型
2)自定义类型
通过dtype将多个相同或者不同的numpy内置类型组合成某种复合类型,用于数组元素的数据类型。除了使用内置类型的全称以外还可以通过类型编码字符串简化类型的说明。
numpy.int8 -> i1
numpy.int16 -> i2
numpy.uint32 -> u4
numpy.float64 -> f8
numpy.complex128 -> c16
对于多字节整数可以加上字节序前缀:
= - 处理器系统默认; < - 小端字节序,低数位低地址; > - 大端字节序,低数位高地址。
98
0x1234
L H
0x34 0x12 L H
0x12 0x34
numpy.str_ -> U字符数
numpy.bool_ -> b
import numpy as np
a = np.array([('ABC', [1, 2, 3])], dtype='U3, 3i4')
print(a)
print(a[0]['f0'])
print(a[0]['f1'][0])
print(a[0]['f1'][1])
print(a[0]['f1'][2])
b = np.array([('ABC', [1, 2, 3])], dtype=[
('name', np.str_, 3), ('scores', np.int32, 3)])
print(b)
print(b[0]['name'])
print(b[0]['scores'][0])
print(b[0]['scores'][1])
print(b[0]['scores'][2])
c = np.array([('ABC', [1, 2, 3])], dtype={
'names': ['name', 'scores'],
'formats': ['U3', '3i4']})
print(c)
print(c[0]['name'])
print(c[0]['scores'][0])
print(c[0]['scores'][1])
print(c[0]['scores'][2])
d = np.array([('ABC', [1, 2, 3])], dtype={
'name': ('U3', 0), 'scores': ('3i4', 12)})
print(d)
print(d[0]['name'])
print(d[0]['scores'][0])
print(d[0]['scores'][1])
print(d[0]['scores'][2])
e = np.array([0x1234], dtype=(
'>u2', {'lo': ('u1', 0), 'hi': ('u1', 1)}))
print('{:x}'.format(e[0]))
print('{:x} {:x}'.format(e['lo'][0], e['hi'][0]))
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
[('ABC', [1, 2, 3])]
ABC
1
2
3
1234
12 34
8.切片
数组[起始:终止:步长, 起始:终止:步长, …]
缺省起始:首(步长为正)、尾(步长为负)
缺省终止:尾后(步长为正)、首前(步长为负)
缺省步长:1
靠近端部的一个或几个连续的维度使用缺省切片,可以用"…"表示。
import numpy as np
a = np.arange(1, 10)
print(a)
print(a[:3]) # 1 2 3
print(a[3:6]) # 4 5 6
print(a[6:]) # 7 8 9
print(a[::-1]) # 9 8 7 6 5 4 3 2 1
print(a[:-4:-1]) # 9 8 7
print(a[-4:-7:-1]) # 6 5 4
print(a[-7::-1]) # 3 2 1
print(a[::]) # 1 2 3 4 5 6 7 8 9
print(a[...]) # 1 2 3 4 5 6 7 8 9
print(a[:]) # 1 2 3 4 5 6 7 8 9
# print(a[]) # error
print(a[::3]) # 1 4 7
print(a[1::3]) # 2 5 8
print(a[2::3]) # 3 6 9
b = np.arange(1, 25).reshape(2, 3, 4)
print(b)
print(b[:, 0, 0]) # 1 13
print(b[0, :, :])
print(b[0, ...])
print(b[0, 1, ::2]) # 5 7
print(b[..., 1])
print(b[:, 1])
print(b[-1, 1:, 2:])
[1 2 3 4 5 6 7 8 9]
[1 2 3]
[4 5 6]
[7 8 9]
[9 8 7 6 5 4 3 2 1]
[9 8 7]
[6 5 4]
[3 2 1]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 4 7]
[2 5 8]
[3 6 9]
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
[ 1 13]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[5 7]
[[ 2 6 10]
[14 18 22]]
[[ 5 6 7 8]
[17 18 19 20]]
[[19 20]
[23 24]]
9.改变维度
1)视图变维:针对一个数组对象获取其不同维度的视图
数组.reshape(新维度)->数组的新维度视图
数组.ravel()->数组的一维视图
2)复制变维:针对一个数组对象获取其不同维度的副本
数组.flatten()->数组的一维副本
3)就地变维
数组.shape = (新维度)
数组.resize(新维度)
4)视图转置
数组.transpose()->数组的转置视图
数组.T: 转置视图属性
至少二维数组才能转置。
import numpy as np
a = np.arange(1, 9)
print(a)
b = a.reshape(2, 4)
print(b)
c = b.reshape(2, 2, 2)
print(c)
d = c.ravel()
print(d)
e = c.flatten()
print(e)
f = b.reshape(2, 2, 2).copy()
print(f)
a += 10
print(a, b, c, d, e, f, sep='\n')
a.shape = (2, 2, 2)
print(a)
a.resize(2, 4)
print(a)
#g = a.transpose()
#g = a.reshape(4, 2)
g = a.T
print(g)
# print(np.array([e]).T)
print(e.reshape(-1, 1))
[1 2 3 4 5 6 7 8]
[[1 2 3 4]
[5 6 7 8]]
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[1 2 3 4 5 6 7 8]
[1 2 3 4 5 6 7 8]
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[11 12 13 14 15 16 17 18]
[[11 12 13 14]
[15 16 17 18]]
[[[11 12]
[13 14]]
[[15 16]
[17 18]]]
[11 12 13 14 15 16 17 18]
[1 2 3 4 5 6 7 8]
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[[[11 12]
[13 14]]
[[15 16]
[17 18]]]
[[11 12 13 14]
[15 16 17 18]]
[[11 15]
[12 16]
[13 17]
[14 18]]
[[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]]
10.组合与拆分
1)垂直组合/拆分
numpy.vstack((上, 下))
numpy.vsplit(数组, 份数)->子数组集合
2)水平组合/拆分
numpy.hstack((左, 右))
numpy.hsplit(数组, 份数)->子数组集合
3)深度组合/拆分
numpy.dstack((前, 后))
numpy.dsplit(数组, 份数)->子数组集合
4)行/列组合
numpy.row_stack((上, 下))
numpy.column_stack((左, 右))
import numpy as np
a = np.arange(11, 20).reshape(3, 3)
b = np.arange(21, 30).reshape(3, 3)
print(a, b, sep='\n')
c = np.vstack((a, b))
print(c)
a, b = np.vsplit(c, 2)
print(a, b, sep='\n')
c = np.hstack((a, b))
print(c)
a, b = np.hsplit(c, 2)
print(a, b, sep='\n')
c = np.dstack((a, b))
print(c)
a, b = np.dsplit(c, 2)
print(a.T[0].T, b.T[0].T, sep='\n')
a = a.ravel()
b = b.ravel()
print(a, b, sep='\n')
c = np.row_stack((a, b))
#c = np.vstack((a, b))
print(c)
#c = np.column_stack((a, b))
#c = np.hstack((a, b))
c = np.c_[a, b]
print(c)
[[11 12 13]
[14 15 16]
[17 18 19]]
[[21 22 23]
[24 25 26]
[27 28 29]]
[[11 12 13]
[14 15 16]
[17 18 19]
[21 22 23]
[24 25 26]
[27 28 29]]
[[11 12 13]
[14 15 16]
[17 18 19]]
[[21 22 23]
[24 25 26]
[27 28 29]]
[[11 12 13 21 22 23]
[14 15 16 24 25 26]
[17 18 19 27 28 29]]
[[11 12 13]
[14 15 16]
[17 18 19]]
[[21 22 23]
[24 25 26]
[27 28 29]]
[[[11 21]
[12 22]
[13 23]]
[[14 24]
[15 25]
[16 26]]
[[17 27]
[18 28]
[19 29]]]
[[11 12 13]
[14 15 16]
[17 18 19]]
[[21 22 23]
[24 25 26]
[27 28 29]]
[11 12 13 14 15 16 17 18 19]
[21 22 23 24 25 26 27 28 29]
[[11 12 13 14 15 16 17 18 19]
[21 22 23 24 25 26 27 28 29]]
[[11 21]
[12 22]
[13 23]
[14 24]
[15 25]
[16 26]
[17 27]
[18 28]
[19 29]]
11.ndarray类的属性
dtype - 元素类型
shape - 数组维度
T - 转置视图
ndim - 维数
size - 元素数, 仅对一维数组等价于len()
itemsize - 元素字节数
nbytes - 总字节数 = size x itemsize
flat - 扁平迭代器
real - 实部数组
imag - 虚部数组
数组.tolist()->列表对象
import numpy as np
a = np.array([
[1 + 1j, 2 + 4j, 3 + 7j],
[4 + 2j, 5 + 5j, 6 + 8j],
[7 + 3j, 8 + 6j, 9 + 9j]])
print(a.dtype, a.dtype.str, a.dtype.char)
print(a.shape)
print(a.ndim)
print(a.size, len(a))
print(a.itemsize)
print(a.nbytes)
print(a.T)
print(a.real, a.imag, sep='\n')
for elem in a.flat:
print(elem)
print(a.flat[[1, 3, 5]])
a.flat[[2, 4, 6]] = 0
print(a)
def fun(a, b):
a.append(b)
return a
x = np.array([10, 20, 30])
y = 40
x = np.array(fun(x.tolist(), y))
print(x)
x = np.append(x, 50)
print(x)
complex128 <c16 D
(3, 3)
2
9 3
16
144
[[ 1.+1.j 4.+2.j 7.+3.j]
[ 2.+4.j 5.+5.j 8.+6.j]
[ 3.+7.j 6.+8.j 9.+9.j]]
[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]]
[[ 1. 4. 7.]
[ 2. 5. 8.]
[ 3. 6. 9.]]
(1+1j)
(2+4j)
(3+7j)
(4+2j)
(5+5j)
(6+8j)
(7+3j)
(8+6j)
(9+9j)
[ 2.+4.j 4.+2.j 6.+8.j]
[[ 1.+1.j 2.+4.j 0.+0.j]
[ 4.+2.j 0.+0.j 6.+8.j]
[ 0.+0.j 8.+6.j 9.+9.j]]
[10 20 30 40]
[10 20 30 40 50]