#每天一点点#
python numpy 篇
1:numpy属性
import numpy as np
array = np.array([[1,2,3],
[2,3,4]])
print(array)
print('number of dim:%s'%array.ndim) #array的几纬
print('shape:',array.shape) #形状 ,X行X列
print('size:%s'%array.size) #大小,元素多少
输出结果 ???????????
输出结果 ??????????
2:numpy 创建array
import numpy as np
a = np.array([2,23,4],dtype=np.float) #默认 float 64位
b = np.array([2,23,4],dtype=np.int) #我的默认 int 32位
print(a.dtype,b.dtype)
输出结果 ? ??? ? float64 int32
a = np.array([[1,2,3],
[2,3,4],
[4,5,6],
[6,7,8]])
print(a) #4行3列的矩阵
b = np.zeros((3,4)) #定义一个3行4列的全部是0的矩阵
c = np.ones((2,3),dtype=np.int) #定义一个2行3列的全部是1的矩阵
d = np.empty((3,4)) #看似empty,实际接近于0
e = np.arange(10,20,2) #10-19之间,步长为2 输出结果:[10 12 14 16 18]
f = np.arange(12).reshape((3,4)) #1-11之间的数字,重新定义它的形状,3行4列
g = np.linspace(1,10,6) #生成一个线段,把1-10平均分成几个线段
h = np.linspace(1,10,6).reshape((2,3)) #把1-10平均分成6个线段,并生成一个2行3列的矩阵
print(b,c,d,e,f,g,h)
尝试每个输出结果
3:numpy的基础运算
3.1 numpy 的基础运算
# numpy 的基础运算
import numpy as np
a = np.array([10,20,30,40])
b = np.arange(4) #0,1,2,3
c = a+b
d = a-b
e = a*b #每个元素相加减乘除
f = b ** 2 #b中每个元素的平方
g = 10*np.sin(a) #对a的每个元素求sin值,然后再乘以10;cos,tan是同样的
#判断某个元素是否小于某个数字
print(b<3) #返回结果 [ True True True False]
3.2 运算二维矩阵
#运算二维矩阵
a1 = np.array([[1,1],[0,1]]) #[[1 1] [0 1]]
b1 = np.arange(4).reshape((2,2)) #[[0 1] [2 3]]
#numpy 中的乘法分两种,一种是逐个相乘,一种是矩阵相乘
c1 = a1*b1 #[[0 1] [0 3]] 逐个相乘
c_dot = np.dot(a1,b1) #[[2 4] [2 3]] 矩阵相乘
c_dot_2 = a1.dot(b1) #效果与c_dot相同
print(c1,c_dot,c_dot_2)
3.3 创建随机array
#创建随机array
a2 = np.random.random((2,4)) #0-1的随机数字,生成2行4列矩阵
#将array求和,最小值,最大值
b2 = np.sum(a2) #求和
c2 = np.min(a2) #最小值
d2 = np.max(a2) #最大值
b21 = np.sum(a2,axis =1) #axis=1行里求和,axis=0 是列里求
c21 = np.min(a2,axis=1) #每一行的最小值都取出
c22 = np.min(a2,axis=0) #每一列的最小值都取出
print(a2,b2,b21,c2,c21,c22)