1 numpy优势
- 用于快速处理任意维度的数组:numpy使用ndarray对象来处理多维数组
- numpy支持常见的数据和矩阵操作
2 ndarray的属性、ndarray的形状、ndarray的类型
import numpy as np
import matplotlib.pyplot as plt
def simple_numpy():
score = np.array(
[[80, 89, 86, 67, 79],
[78, 97, 89, 67, 81],
[90, 94, 78, 67, 74],
[91, 91, 90, 67, 69],
[76, 87, 75, 67, 86],
[70, 79, 84, 67, 84],
[94, 92, 93, 67, 64],
[86, 85, 83, 67, 80]]
)
print(score)
print(score.shape)
print(score.ndim)
print(score.size)
print(score.itemsize)
print(score.dtype)
a = np.array([1,2,3])
print(a.shape)
b = np.array([[1,2,3], [4,5,6]])
print(b.shape)
c = np.array([[[1,2,3], [4,5,6]],[[1,2,3], [4,5,6]]])
print(c.shape)
ar = np.array(['abc','www', 'wwwa'], dtype=np.string_)
print(ar.dtype)
3 数组的基本操作
def basic_numpy():
ones = np.ones([4, 8])
print(ones)
zeros= np.zeros_like(ones)
print(zeros)
a = np.array([[1,2,3],[4,5,6]])
a1 = np.array(a)
print(a1)
a2 = np.asarray(a)
a[0,0] = 100
print(a1)
print(a2)
m = np.linspace(0, 100, 11)
print(m)
m2 = np.arange(10, 50, 2)
print(m2)
m3 = np.logspace(0, 2, 3)
print(m3)
4 生成随机数组
def suijishuzu():
stock_change = np.random.normal(loc=0, scale=1, size=(4,5))
plt.figure(figsize=(10,4), dpi=100)
plt.plot(stock_change)
plt.show()
5 数组的索引、切片
def suoyin_qiepian():
stock_change = np.random.normal(loc=0, scale=1, size=(4, 5))
print(stock_change[0, 0:3])
a1 = np.array([[[1, 2, 3], [4, 5, 6]],
[[12, 3, 34], [5, 6, 7]]])
print(a1[1,0,0])
6 ndarray的运算
1. 通用判断函数:
np.all(score[0:2, :] > 60) 判断前两名同学的成绩[0:2, :]是否全及格
np.any(score[0:2, :] > 80) 判断前两名同学的成绩[0:2, :]是否有大于80分的
2.np.where(三元运算符):
temp = score[:4, :4] 前四名学生,前四门课程
np.where(temp > 60, 1, 0) 成绩中大于60的置为1,否则为0
np.where(np.logical_and(temp > 60, temp < 90), 1, 0) 成绩中大于60且小于90的换为1,否则为0
np.where(np.logical_or(temp > 90, temp < 60), 1, 0) 成绩中大于90或小于60的换为1,否则为0
3. 统计运算:axis 轴的取值并不一定,需要注意
np.max() :找到最大值
np.min()
np.mean()
np.std()
np.var()
np.argmax() :找到最大值对应的索引下标
np.argmin() :找到最小值对应的索引下标
def ndarray_yunsuan():
score = np.random.randint(40, 100, (10, 5))
test_score = score[6:, 0:5]
print(test_score)
print(test_score>60)
test_score[test_score>60] = 1
print(test_score)