NumPy学习

1. 安装和学习

2. ndarray

import numpy as np
# 一维数列
a1 = np.array([1, 2, 3])
print(a1)
# 二维数列
a2 = np.array([[1, 2], [3, 4]])
print(a2)
# 定义最小维度
a3 = np.array([1, 2, 3, 4], ndmin=2)
print(a3)
# 指定数据类型
a4 = np.array([1, 2, 3], dtype=np.float32)
print(a4)

3. 数据类型

import numpy as np
# 使用标量类型
dt1 = np.dtype(np.int32)
print(dt1)
# int8, int16, int32, int64 四种数据类型可以使用字符串 'i1', 'i2','i4','i8' 代替
dt2 = np.dtype('i4')
print(dt2)
# 还可以像结构体一样用
student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])
a = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student)
print(a)
print(a['name'])
print(a[1])

4. 数组属性

import numpy as np

a = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
# 维度
print(a.ndim)
# 各维度大小
print(a.shape)
# 现在调整其大小
a.shape = (4, 2)
print(a)
b = a.reshape(2, 4)
print(b)
print(b.ndim)
# b 现在拥有三个维度
b = a.reshape(2, 1, 4)  
print(b)
print(b.ndim)
# 数组元素的字节大小  
x = np.array([1,2,3], dtype = np.int8)  
print (x.itemsize)

5.特殊数组

import numpy as np
# 未初始化的数组
x = np.empty([3, 2], dtype=int)
print(x)
# 元素为零
# 默认为浮点数
x = np.zeros(5)
print(x)
# 设置类型为整数
y = np.zeros((5, ), dtype=np.int)
print(y)
# 自定义类型
z = np.zeros((2, 2), dtype=[('x', 'i4'), ('y', 'f4')])
print(z)
# 对角矩阵
x = np.eye(4)
print(x)
# 从列表或元组转换
# numpy.asarray(a, dtype = None, order = None)
x = [1, 2, 3]
a = np.asarray(x)
print(a)
x[0] = 0
print(x)
# 序列
# numpy.arange(start, stop, step, dtype)
x = np.arange(10, 20, 2)
print(x)
# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
x = np.linspace(10, 20, 6)
print(x)
# 重复
b = np.array([1, 2, 3])
bb = np.tile(b, (2, ))
print(bb)

6. 数组切片

import numpy as np

a = np.arange(10)
print(a)
s = slice(2, 7, 2)  # 从索引 2 开始到索引 7 停止,间隔为2
print(a[s])
b = a[2:7:2]  # 效果同上
print(b)

a = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a)
# 从某个索引处开始切割
print(a[1:, 1:])
print(a[1:, [1, 2]])
print(a[:, 0])  #获取列元素

7. 高级索引

import numpy as np

x = np.array([[1, 2], [3, 4], [5, 6]])
y = x[[0, 1, 2], [0, 1, 0]]  #获取数组中(0,0),(1,1)和(2,0)位置处的元素
print(y)

x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
rows = np.array([[0, 0], [3, 3]])
cols = np.array([[0, 2], [0, 2]])  # 获取四个角元素
y = x[rows, cols]
print(y)
# 通过判断布尔
x[x > 5] = 0
print(x)
# 通过索引
x = np.arange(32).reshape((8, 4))
print(x[[4, 2, 1, 7]])
x = np.arange(32).reshape((8, 4))
print(x[np.ix_([0, 1, 6, 7], [3, 2, 1, 0])])
最后修改:2019 年 10 月 21 日
你的赞赏是我前进的动力