numpy系列笔记一数组创建and常见函数使用and计算规则

数组创建
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))

在这里插入图片描述

常用函数
  1. .dtype 查看数据类型和存储的字节数
  2. .shape 数组维度
  3. .reshape() 重新指定数组维度,需要参数(重新指定的维度中总的数据个数要与原数组中的数据个数相等)
  4. .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被认为是一个很小很小的数

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值