array([1, 2, 3, 4])
numpy 索引和切片
1 # 基本索引
2 ar = np.arange(20)
3 # print(ar)
4 # print(ar[4])
5 # print(ar[:3])
6 # 一维的
7 ar = np.arange(16).reshape(4,4)
8 print(ar)
9 # print(ar[0]) # 切出一行 切片为下一个维度的一个元素
10 # print(ar[0][-1]) # 二次索引,获得一维中的一个值
11 print(ar[:3]) # 切出多行,
12 print(ar[1,1]) # 相似于二次索引
13 print(ar[:2, 1:])
14 # 二维的
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
5
[[1 2 3]
[5 6 7]]
1 # 布尔型索引
2 ar = np.arange(12).reshape(3,4)
3 i = np.array([True, False, True])
4 j = np.array([False, True, False, True])
5 # print(ar)
6 # print(i)
7 # print(j)
8 # print(ar[i])
9 # print(ar[i,:]) # 选行
10 # print(ar[:, j]) # 选列
11 # 基本的布尔型索引
12 ai = ar > 5
13 print(ar)
14 print(ai)
15 print(ar[ar % 2 != 0]) # 选取全部的奇数
16 print(ar[i,j])
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[False False False False]
[False False True True]
[ True True True True]]
[ 1 3 5 7 9 11]
[ 1 11]
numpy 随机数
numpy.random数组
1 # 生成
2 samples = np.random.normal(size=(4,4)) # 符合标准正态分布的4*4样本值
3 print(samples)
[[ 0.85235645 0.85512049 -0.29868382 1.03635971]
[-1.42338011 -1.20987794 1.74704175 0.08565753]
[ 1.11191625 0.5263941 0.21444175 0.08820261]
[ 0.60592032 0.93473874 -0.28916297 -1.41480416]]
1 # numpy.random.rand() : [0, 1) 之间的随机样本或N维浮点数组 ---均匀分布
2 import matplotlib.pyplot as plt
3
4 a = np.random.rand()
5 b = np.random.rand(4)
6 c = np.random.rand(3,4)
7 s1 = np.random.rand(1000)
8 s2 = np.random.rand(1000)
9 plt.scatter(s1, s2)
10 plt.show()

1 # numpy.random.randn() :生成一个浮点数或者N维的浮点数组---正态分布
2 s1 = np.random.randn(1000)
3 s2 = np.random.randn(1000)
4 plt.scatter(s1, s2)
5 plt.show()

1 # numpy.random.randint(low, high=None, size=None, dtype='l'): 生成一个整数或者N维的整数数组
2 # 若high不为None时,取[low,high)之间随机整数,不然取值[0,low)之间随机整数,且high必须大于low
3 # dtype参数:只能是int类型
4 np.random.randint(2)
5 np.random.randint(2, 6, size=5)
6 np.random.randint(1,100, size=[3,5])
array([[30, 84, 1, 94, 18],
[95, 57, 92, 38, 82],
[95, 25, 33, 74, 57]])
numpy的输入输出
读写数组数据,文本数据dom
1 # 二进制文件
2 # 存数据
3 import numpy as np
4 ar = np.random.rand(5,5)
5 np.save('test.npy',ar)
6 np.load('test.npy')
array([[0.61427194, 0.69416288, 0.1939631 , 0.60784977, 0.25270645],
[0.27015826, 0.21855706, 0.86313053, 0.81490094, 0.72308043],
[0.95732625, 0.08912547, 0.58596282, 0.75812357, 0.43485775],
[0.41967473, 0.42947078, 0.98010856, 0.26209422, 0.69600965],
[0.95892746, 0.48951498, 0.98279041, 0.44956069, 0.41290226]])
1 # 文本数据
2 # 存
3 np.savetxt('test.txt', ar, delimiter=',')
1 # 读取
2 np.loadtxt('test.txt', delimiter=',')
array([[0.61427194, 0.69416288, 0.1939631 , 0.60784977, 0.25270645],
[0.27015826, 0.21855706, 0.86313053, 0.81490094, 0.72308043],
[0.95732625, 0.08912547, 0.58596282, 0.75812357, 0.43485775],
[0.41967473, 0.42947078, 0.98010856, 0.26209422, 0.69600965],
[0.95892746, 0.48951498, 0.98279041, 0.44956069, 0.41290226]])总结思惟导图:https://img2018.cnblogs.com/blog/1816772/201910/1816772-20191023000450837-1220857330.png