Numpy 基本操作,持续更新...
1.导入numpy 包
import numpy as np
2.建立array 查看数据类型
x1 = np.array([1,2,3,4])
x1.dtype #查看类型,数值型
注意,当数据中混有多种数据类型时,会识别为字符型:
x2 = np.array([
[1,2,3,'4'],
[2,3,4,5]
])
x2.dtype #result dtype('<U11')
3.np.array 的索引
print(x2[0,3]) #索引,第0行第4列
print(x2[:,1:3]) #索引,取第一列和第二列
vector = np.array([5,10,15,20])
vector == 10 # '=='对array中的每一个元素进行判断,返回布尔类型结果
v2 = (x2 == '4')
print(x2[v2]) #布尔类型array作为索引
4.改变array 元素类型
print(x3.dtype)
x3_1 = x3.astype('str')
print(x3_1.dtype)#x3 int32, x3_1 <U11.
5.求最大值,最小值,求和
x3.min()#min value
x3.max()#max value
x3.sum(axis = 1) #行求和, axis = 0 列求和
6.常用函数
np.zeros((3,4))#得到3行4列零矩阵,1矩阵为np.ones()
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
np.arange(10,30,5) #生成一个序列,到30之前为止。
array([10, 15, 20, 25])
np.arange(12).reshape(4,3) #reshape
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
np.random.random((2,3)) #generate random value
from numpy import pi
np.linspace(0,0.2*pi,10) #取均值为0.2*pi
7.矩阵运算
a = np.array([20,30,40,50])
b = np.arange(4)
c = a -b
print(a,b,c) # + - * / **皆可
A = np.array([
[1,1],
[0,1]
])
B = np.array([
[2,0],
[3,4]
])
print(A*B) #点乘
print(A.dot(B)) #叉乘