python--numpy

  1. 查看numpy.array的基本信息
import numpy as np

ar = np.array([1,2,3,4,5,6,7])
print(ar)          # 输出数组,注意数组的格式:中括号,元素之间没有逗号(和列表区分)
print(ar.ndim)     # 输出数组维度的个数(轴数),或者说“秩”,维度的数量也称rank
print(ar.shape)    # 数组的维度,对于n行m列的数组,shape为(n,m)
print(ar.size)     # 数组的元素总数,对于n行m列的数组,元素总数为n*m
print(ar.dtype)    # 数组中元素的类型,类似type()(注意了,type()是函数,.dtype是方法)
print(ar.itemsize) # 数组中每个元素的字节大小,int32l类型字节为4,float64的字节为8
print(ar.data)     # 包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。
  1. 生成序列
# 创建数组:linspace():返回在间隔[开始,停止]上计算的num个均匀间隔的样本。

ar1 = np.linspace(2.0, 3.0, num=5)

# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# start:起始值,stop:结束值
# num:生成样本数,默认为50
# endpoint:如果为真,则停止是最后一个样本。否则,不包括在内。默认值为True。
# retstep:如果为真,返回(样本,步骤),其中步长是样本之间的间距 → 输出为一个包含2个元素的元祖,第一个元素为array,第二个为步长实际值
  1. 创建数组:zeros()/zeros_like()/ones()/ones_like()
    ones()/ones_like()zeros()/zeros_like()一样,只是填充为1
ar1 = np.zeros(5)  
ar2 = np.zeros((2,2), dtype = np.int)
print(ar1,ar1.dtype)
print(ar2,ar2.dtype)
print('------')
# numpy.zeros(shape, dtype=float, order='C'):返回给定形状和类型的新数组,用零填充。
# shape:数组纬度,二维以上需要用(),且输入参数为整数
# dtype:数据类型,默认numpy.float64
# order:是否在存储器中以C或Fortran连续(按行或列方式)存储多维数据。C是按行排

ar3 = np.array([list(range(5)),list(range(5,10))])
ar4 = np.zeros_like(ar3)
print(ar3)
print(ar4)
print('------')
# 返回具有与给定数组相同的形状和类型的零数组,这里ar4根据ar3的形状和dtype创建一个全0的数组
  1. 切片
ar = np.arange(12).reshape(3,4)
m = ar > 5
print(m)  # 这里m是一个判断矩阵
print(ar[m])  # 用m判断矩阵去筛选ar数组中>5的元素 → 重点!后面的pandas判断方式原理就来自此处

[[False False False False]
 [False False  True  True]
 [ True  True  True  True]]
[ 6  7  8  9 10 11]
  1. 随机模块
numpy.random.rand(d0, d1, ..., dn):生成一个[0,1)之间的随机浮点数或N维浮点数组 —— 均匀分布
numpy.random.randn(d0, d1, ..., dn):生成一个浮点数或N维浮点数组 —— 正态分布
numpy.random.randint(low, high=None, size=None, dtype='l'):生成一个整数或N维整数数组
# 若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数,且high必须大于low 
# dtype参数:只能是int类型 
  1. 数组类型转换:.astype()
ar1 = np.arange(10,dtype=float)
print(ar1,ar1.dtype)
print('-----')
# 可以在参数位置设置数组类型

ar2 = ar1.astype(np.int32)
print(ar2,ar2.dtype)
print(ar1,ar1.dtype)
# a.astype():转换数组类型
# 注意:养成好习惯,数组类型用np.int32,而不是直接int32
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] float64
-----
[0 1 2 3 4 5 6 7 8 9] int32
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] float64
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值