数组创建
import numpy as np
#方式一
a=np.array([1,2,3])
print(a)
print(type(a))
#方式二
b=np.array(range(1,6))
print(b)
print(type(b))
#方式三
c=np.arange(1,6)
print(c)
print(type(c))
常用函数
- .dtype 查看数据类型和存储的字节数
- .shape 数组维度
- .reshape() 重新指定数组维度,需要参数(重新指定的维度中总的数据个数要与原数组中的数据个数相等)
- .flatten() 将数组转换为一维数组,不需要参数
.dtype
import numpy as np
c=np.arange(1,6)
print(c)
print(type(c))
print(c.dtype)#数据的类型
d=np.array(range(1,4),dtype="int8")#手动指定数据类型
print(d)
print(d.dtype)
#调整已有数据的数据类型
d=d.astype("int32")
print(d)
print(d.dtype)
.shape
import numpy as np
a=np.array([[0,4,5,6,7,8],[4,5,6,7,8,9]])
print(a)
print(a.shape)
b=np.array([[[0,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(b)
print(b.shape)
.reshape()
import numpy as np
b=np.array([[[0,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(b.shape)
c=b.reshape(2,6)#重新指定数组的维度
print(c)
print(c.shape)
d=c.reshape(12)#变为一维数组
print(d)
#当不知道是数据有多少时如何将数据转换为一维数组
e=c.reshape(c.shape[0]*c.shape[1])#.shape[0]代表原数组有多少行;.shape[1]代表原数组有多少列
print(e)
.flatten()
import numpy as np
b=np.array([[[0,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(b.shape)
g=b.flatten()
print(g)
计算规则
1.数组和数进行计算
数组中的每个值都会和数进行运算
2.格式相同的数组进行计算
当两个格式相同的数组进行计算时,计算规则为对应位置的值进行运算
3.当两个格式不一样的数组进行计算时
如果两个数组在某一维度上一样时,在这个维度进行计算,若果找不到相同的维度则无法进行计算
广播原则
如果两个数组的后援维度(从末尾开始算起的维度)的轴长度相符或其中一个方向的长度为一,则认为他们是广播兼容的。广播会在缺失或长度为一的维度上进行
import numpy as np
x=np.arange(0,6)
print(x)
print(x.shape)
y=np.array([[0,1,2,3,4,5],[6,7,8,9,10,11],[12,13,14,15,16,17]])
print(y)
print(y.shape)
print(y-x)
数组除于0
import numpy as np
e=np.array([0,4,5,6,7,8])
print(e/0)#除于0
#nan代表:不是一个数,inf表示一个无穷大的数,应为在这里0被认为是一个很小很小的数