Python数据分析–numpy总结
NumPy常用方法总结 ![在这里插入图片描述](https://res.hc-cdn.com/ecology/7.2.105/v2_resources/ydcomm/libs/images/loading.gif)
文章目录
Python数据分析--numpy总结
生成ndarray的几种方式
从已有数据中创建
利用random模块生成ndarray
创建特定形状的多维数组
利用arange函数
存取元素
矩阵操作
数据合并与展平
合并一维数组
多维数组的合并
矩阵展平
通用函数
使用math与numpy函数性能比较:
使用循环与向量运算比较:
广播机制
生成ndarray的几种方式
从已有数据中创建
import numpy as np
list1 = [3.14,2.17,0,1,2]
nd1 = np.array(list1)
print(nd1)
print(type(nd1))
1
2
3
4
5
[3.14 2.17 0. 1. 2. ]
1
2
list2 = [[3.14,2.17,0,1,2],[1,2,3,4,5]]
nd2 = np.array(list2)
print(nd2)
print(type(nd2))
1
2
3
4
5
[[3.14 2.17 0. 1. 2. ]
[1. 2. 3. 4. 5. ]]
1
2
3
利用random模块生成ndarray
import numpy as np
nd5 = np.random.random([3,3])
print(nd5)
print(type(nd5))
1
2
3
4
5
6
[[0.31192569 0.3022696 0.48253531]
[0.38008201 0.59103878 0.98225759]
[0.54242215 0.14208123 0.59577163]]
1
2
3
4
import numpy as np
np.random.seed(123)
nd5_1 = np.random.randn(2,3)
print(nd5_1)
np.random.shuffle(nd5_1)
print("随机打乱后数据")
print(nd5_1)
print(type(nd5_1))
1
2
3
4
5
6
7
8
9
10
[[-1.0856306 0.99734545 0.2829785 ]
[-1.50629471 -0.57860025 1.65143654]]
随机打乱后数据
[[-1.50629471 -0.57860025 1.65143654]
[-1.0856306 0.99734545 0.2829785 ]]
1
2
3
4
5
6
创建特定形状的多维数组
import numpy as np
#生成全是0的3x3矩阵
nd6 = np.zeros([3,3])
#生成全是1的3x3矩阵
nd7 = np.ones([3,3])
#生成3阶的单位矩阵
nd8= np.eye(3)
#生成3阶对角矩阵
print (np.diag([1, 2, 3]))
1
2
3
4
5
6
7
8
9
10
11
[[1 0 0]
[0 2 0]
[0 0 3]]
1
2
3
import numpy as np
nd9 = np.random.random([5,5])
np.savetxt(X=nd9,fname='./test2.txt')
nd10 = np.loadtxt('./test2.txt')
1
2
3
4
5
利用arange函数
import numpy as np
print(np.arange(10))
print(np.arange(0,10))
print(np.arange(1, 4,0.5))
print(np.arange(9, -1, -1))
1
2
3
4
5
6
7
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[1. 1.5 2. 2.5 3. 3.5]
[9 8 7 6 5 4 3 2 1 0]
1
2
3
4
存取元素
import numpy as np
np.random.seed(2018)
nd11 = np.random.random([10])
#获取指定位置的数据,获取第4个元素
nd11[3]
#截取一段数据
nd11[3:6]
#截取固定间隔数据
nd11[1:6:2]
#倒序取数
nd11[::-2]
#截取一个多维数组的一个区域内数据
nd12=np.arange(25).reshape([5,5])
nd12[1:3,1:3]
#截取一个多维数组中,数值在一个值域之内的数据
nd12[(nd12>3)&(nd12 |