【Python科学计算】numpy——python 矩阵
目录
0. numpy 的数据类型
| 名称 | 描述 |
|---|---|
| bool_ | 布尔型数据类型(True 或者 False) |
| int_ | 默认的整数类型(类似于 C 语言中的 long,int32 或 int64) |
| intc | 与 C 的 int 类型一样,一般是 int32 或 int 64 |
| intp | 用于索引的整数类型(类似于 C 的 ssize_t,一般情况下仍然是 int32 或 int64) |
| int8 | 字节(-128 to 127) |
| int16 | 整数(-32768 to 32767) |
| int32 | 整数(-2147483648 to 2147483647) |
| int64 | 整数(-9223372036854775808 to 9223372036854775807) |
| uint8 | 无符号整数(0 to 255) |
| uint16 | 无符号整数(0 to 65535) |
| uint32 | 无符号整数(0 to 4294967295) |
| uint64 | 无符号整数(0 to 18446744073709551615) |
| float_ | float64 类型的简写 |
| float16 | 半精度浮点数,包括:1 个符号位,5 个指数位,10 个尾数位 |
| float32 | 单精度浮点数,包括:1 个符号位,8 个指数位,23 个尾数位 |
| float64 | 双精度浮点数,包括:1 个符号位,11 个指数位,52 个尾数位 |
| complex_ | complex128 类型的简写,即 128 位复数 |
| complex64 | 复数,表示双 32 位浮点数(实数部分和虚数部分) |
| complex128 | 复数,表示双 64 位浮点数(实数部分和虚数部分) |
1. 导入 numpy 包
import numpy as np
2. 建立 0 矩阵
下面的代码体现了如何构建一个 3 行 4 列的整型全0矩阵:
x = np.zeros((3,4), dtype = np.int)
print(x)
结果:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
3. 建立 1 矩阵
下面的代码体现了如何构建一个 3 行 4 列的浮点型全1矩阵:
x = np.ones((3,4), dtype = np.float)
print(x)
结果:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
4. 修改矩阵元素值并查看类型
下面的代码体现了构建一个 3 行 4 列的浮点型全1矩阵后,将 2 行 3 列的元素修改为 5,查看该处的值与类型:
x = np.ones((3,4), dtype = np.float)
print(x)
x[2][3]=5
print()
print(x[2][3])
print()
print(x)
print()
print(x[2][3].dtype)
结果:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
5.0
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 5.]]
float64
5. 创建数值范围矩阵
下面的代码体现了构建一个 起点为 0 ,终点为 10,步长为 1 ,类型为整型的由数值范围构建的矩阵:
# numpy.arange(start, stop, step, dtype)
x=np.arange(0,10,1,dtype=np.int)
print(x)
结果:
[0 1 2 3 4 5 6 7 8 9]
6. 将Python的类型转换为 Numpy 的矩阵类型
下面的代码体现了将 python 的 list 列表 转换为 浮点型矩阵 的例子:
# numpy.asarray(a, dtype = None, order = None)
x=[1,2,3,4,5]
print(type(x))
print(x)
y=np.asarray(x,dtype=float)
print(type(y))
print(y)
结果:
<class \'list\'>
[1, 2, 3, 4, 5]
<class \'numpy.ndarray\'>
[1. 2. 3. 4. 5.]
7. 获得矩阵的规模和维度
下面的代码体现了构建一个 3 行 4 列的浮点型全1矩阵后,获取它的行列数和维度的例子:
x = np.ones((3,4), dtype = np.float)
print(x)
print("维度:"+str(x.ndim))
s=x.shape
print(s)
print(str(s[0])+"行"+str(s[1])+"列")
结果:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
维度:2
(3, 4)
3行4列
8. 调整矩阵的大小
下面的代码体现了一个将 1行10列 的矩阵转为 5行2列 的矩阵的例子:
x=np.arange(0,10,1,dtype=np.int)
print(x.shape)
print(x)
print()
x=x.reshape(5,2)
print(x.shape)
print(x)
结果:
(10,)
[0 1 2 3 4 5 6 7 8 9]
(5, 2)
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]